JAVA PROGRAMMING
1. Write a Java program that prompts the user for an integer and then prints out
all the prime numbers up to that Integer?
import [Link];
public class PrimeNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter an integer: ");
int n = [Link]();
[Link]("Prime numbers up to " + n + " are:");
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
[Link](i + " ");
}
}
}
static boolean isPrime(int num) {
if (num <= 1) return false;
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) return false;
}
return true;
}
}
OUTPUT
Enter an integer: 20
Prime numbers up to 20 are:
2 3 5 7 11 13 17 19
2. Write a Java program to multiply two given matrices.
public class MatrixMultiplication {
public static void main(String[] args) {
int[][] A = { {1, 2}, {3, 4} };
int[][] B = { {5, 6}, {7, 8} };
int rowsA = [Link];
int colsA = A[0].length;
int colsB = B[0].length;
int[][] result = new int[rowsA][colsB];
for (int i = 0; i < rowsA; i++) {
for (int j = 0; j < colsB; j++) {
for (int k = 0; k < colsA; k++) {
result[i][j] += A[i][k] * B[k][j];
}
}
}
[Link]("Result of Matrix Multiplication:");
for (int[] row : result) {
for (int val : row) {
[Link](val + " ");
}
[Link]();
}
}
}
OUTPUT
Result of Matrix Multiplication:
19 22
43 50
3. Write a Java program that displays the number of characters, lines and words
in a text?
import [Link];
public class TextAnalysis {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter text (type 'END' on a new line to finish):");
int charCount = 0, wordCount = 0, lineCount = 0;
while (true) {
String line = [Link]();
if ([Link]("END")) break;
lineCount++;
charCount += [Link]();
wordCount += [Link]("\\s+").length;
}
[Link]("Characters: " + charCount);
[Link]("Words: " + wordCount);
[Link]("Lines: " + lineCount);
}
}
OUTPUT
Enter text (type 'END' on a new line to finish):
computer science with data science
I year
End
END
Characters: 43
Words: 8
Lines: 3
4. Generate random numbers between two given limits using Random class and
print messages according to the range of the value generated.
import [Link];
import [Link];
public class RandomRange {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter lower limit: ");
int low = [Link]();
[Link]("Enter upper limit: ");
int high = [Link]();
Random rand = new Random();
int num = [Link](high - low + 1) + low;
[Link]("Generated number: " + num);
if (num < (low + high) / 2) {
[Link]("Number is in the lower half of the range.");
} else {
[Link]("Number is in the upper half of the range.");
}
}
}
OUTPUT
Enter lower limit: 42
Enter upper limit: 77
Generated number: 67
Number is in the upper half of the range.
ANOTHER OUTPUT SHOULD NOT DO!!
Enter lower limit: 200
Enter upper limit: 100
ERROR!
5. Write a program to do String Manipulation using Character Array and
perform the following string operations: a) String length
b) Finding a character at a particular position
c) Concatenating two strings
d)
public class CharArrayStringOps {
public static void main(String[] args) {
char[] str1 = {'H','e','l','l','o'};
char[] str2 = {'W','o','r','l','d'};
// a) String length
[Link]("Length of str1: " + [Link]);
// b) Character at position
int pos = 2;
[Link]("Character at position " + pos + " in str1: " + str1[pos]);
// c) Concatenation
char[] concat = new char[[Link] + [Link]];
[Link](str1, 0, concat, 0, [Link]);
[Link](str2, 0, concat, [Link], [Link]);
[Link]("Concatenated string: " + new String(concat));
}
}
OUTPUT
Length of str1: 5
Character at position 2 in str1: l
Concatenated string: HelloWorld
6. Write a program to perform the following string operations using String
class: a) String Concatenation
b) Search a substring
c) To extract substring from given string
public class StringOps {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
// a) Concatenation
String concat = str1 + " " + str2;
[Link]("Concatenated String: " + concat);
// b) Search substring
String search = "lo";
[Link]("Substring '" + search + "' found at index: " + [Link](search));
// c) Extract substring
String sub = [Link](0, 5);
[Link]("Extracted substring: " + sub);
}
}
OUTPUT
Concatenated String: Hello World
Substring 'lo' found at index: 3
Extracted substring: Hello
7. Write a program to perform string operations using StringBuffer class: a)
Length of a string
b) Reverse a string
c) Delete a substring from the given string
public class StringBufferOps {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("HelloWorld");
// a) Length
[Link]("Length: " + [Link]());
// b) Reverse
[Link]("Reversed: " + [Link]());
// c) Delete substring
sb = new StringBuffer("HelloWorld");
[Link](2, 5);
[Link]("After deletion: " + sb);
}
}
OUTPUT
Length: 10
Reversed: dlroWolleH
After deletion: HeWorld
9. Write a threading program which uses the same method asynchronously
to print the numbers 1 to 10 using Thread1 and to print 90 to 100 using
Thread2.
public class AsyncPrintSameMethod {
static class Printer implements Runnable {
private final int start, end;
Printer(int start, int end) {
[Link] = start;
[Link] = end;
}
// Same method used by both threads (no synchronization ->
asynchronous/interleaved)
private void printRange() {
for (int i = start; i <= end; i++) {
[Link]([Link]().getName() + ": " + i);
try {
[Link](100); // small delay to visualize interleaving
} catch (InterruptedException e) {
[Link]().interrupt();
}
}
}
@Override
public void run() {
printRange();
}
}
public static void main(String[] args) {
Thread t1 = new Thread(new Printer(1, 10), "Thread1");
Thread t2 = new Thread(new Printer(90, 100), "Thread2");
[Link]();
[Link]();
}
}
OUTPUT
Thread2: 90
Thread1: 1
Thread2: 91
Thread1: 2
Thread2: 92
Thread1: 3
Thread2: 93
Thread1: 4
Thread2: 94
Thread1: 5
Thread2: 95
Thread1: 6
Thread2: 96
Thread1: 7
Thread2: 97
Thread1: 8
Thread2: 98
Thread1: 9
Thread2: 99
Thread1: 10
Thread2: 100
10. Write a program to demonstrate the use of following exceptions.
a) Arithmetic Exception
b) Number Format Exception
c) Array Index Out of Bound Exception
Negative Array Size Exception
public class ExceptionDemo {
public static void main(String[] args) {
// a) ArithmeticException (divide by zero)
try {
int a = 10, b = 0;
int c = a / b;
[Link]("Result: " + c);
} catch (ArithmeticException e) {
[Link]("ArithmeticException caught: " + [Link]());
}
// b) NumberFormatException
try {
String s = "12a3";
int n = [Link](s);
[Link]("Parsed: " + n);
} catch (NumberFormatException e) {
[Link]("NumberFormatException caught: " + [Link]());
}
// c) ArrayIndexOutOfBoundsException
try {
int[] arr = {1, 2, 3};
[Link](arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("ArrayIndexOutOfBoundsException caught: " + [Link]());
}
// d) NegativeArraySizeException
try {
int[] bad = new int[-5];
} catch (NegativeArraySizeException e) {
[Link]("NegativeArraySizeException caught: " + [Link]());
}
}
}
ArithmeticException caught: / by zero
NumberFormatException caught: For input string: "12a3"
ArrayIndexOutOfBoundsException caught: Index 5 out of bounds for length 3
NegativeArraySizeException caught: -5