0% found this document useful (0 votes)
3 views17 pages

Java Sample Program

The document contains multiple Java programs demonstrating various functionalities including prime number generation, matrix multiplication, text analysis, random number generation, string manipulation, threading, and exception handling. Each program is structured with user prompts for input and outputs results based on the specified operations. The programs cover fundamental concepts in Java programming such as loops, conditionals, arrays, and exception management.

Uploaded by

akareem97966
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views17 pages

Java Sample Program

The document contains multiple Java programs demonstrating various functionalities including prime number generation, matrix multiplication, text analysis, random number generation, string manipulation, threading, and exception handling. Each program is structured with user prompts for input and outputs results based on the specified operations. The programs cover fundamental concepts in Java programming such as loops, conditionals, arrays, and exception management.

Uploaded by

akareem97966
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

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 java.util.Scanner;

public class PrimeNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
System.out.println("Prime numbers up to " + number + ":");
for (int i = 2; i <= number; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}

public static boolean isPrime(int num) {


if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
2. Write a Java program to multiply two given matrices.

import java.util.Scanner;

public class MatrixMultiplication {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Get dimensions of matrices
System.out.print("Enter the number of rows of matrix 1: ");
int rows1 = scanner.nextInt();
System.out.print("Enter the number of columns of matrix 1: ");
int cols1 = scanner.nextInt();
System.out.print("Enter the number of rows of matrix 2: ");
int rows2 = scanner.nextInt();
System.out.print("Enter the number of columns of matrix 2: ");
int cols2 = scanner.nextInt();
// Check if matrices can be multiplied
if (cols1 != rows2) {
System.out.println( "Matrix multiplication not possible. The number of columns
of matrix 1 must be equal to the number of rows of matrix 2.");
return;
}
// Create matrices
int[][] matrix1 = new int[rows1][cols1];
int[][] matrix2 = new int[rows2][cols2];
int[][] result = new int[rows1][cols2];
// Get elements of matrices
System.out.println("Enter elements of matrix 1:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i][j] = scanner.nextInt();
}
}
System.out.println("Enter elements of matrix 2:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = scanner.nextInt();
}
}
// Multiply matrices
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
for (int k = 0; k < cols1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
// Print result
System.out.println("Resultant matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}
}
}
3. Write a Java program that displays the number of characters, lines and words
in a text?

import java.util.Scanner;

public class TextAnalyzer {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Prompt the user for text input
System.out.println("Enter your text: ");
String inputText = scanner.nextLine();
// Count the number of characters (including spaces)
int charCount = inputText.length();
// Count the number of words by splitting by spaces
String[] words = inputText.trim().split("\\s+");
int wordCount = words.length;
// Count the number of lines by splitting by newline characters (though in
// single-line input, it will always be 1)
String[] lines = inputText.split("\\r?\\n");
int lineCount = lines.length;
// Display the results
System.out.println("Number of characters (including spaces): " + charCount);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of lines: " + lineCount);
scanner.close();
}
}
4. Generate random numbers between two given limits using Random class and
print messages according to the range of the value generated.

import java.util.Scanner;
import java.util.Random;

public class RandomNumberGenerator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the lower limit: ");
int lowerLimit = scanner.nextInt();
System.out.print("Enter the upper limit: ");
int upperLimit = scanner.nextInt();
Random random = new Random();
int randomNumber = random.nextInt(upperLimit - lowerLimit + 1) +
lowerLimit;
System.out.println("Random number generated: " + randomNumber);
if (randomNumber < lowerLimit + 10) {
System.out.println("The random number is close to the lower limit.");
} else if (randomNumber > upperLimit - 10) {
System.out.println("The random number is close to the upper limit.");
} else {
System.out.println("The random number is in the middle range.");
}
}
}
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

import java.util.Scanner;

public class StringManipulation {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a word: ");
String str1 = scanner.nextLine();
System.out.print("Enter another word: ");
String str2 = scanner.nextLine();
// a) String length
int length1 = str1.length();
System.out.println("Length of str1: " + length1);
// b) Finding a character at a particular position
System.out.print("Enter an index: ");
int index = scanner.nextInt();
if (index >= 0 && index < str1.length()) {
char character = str1.charAt(index);
System.out.println("Character at index " + index + " in str1: " + character);
} else {
System.out.println("Invalid index.");
}
// c) Concatenating two strings
String concatenatedString = str1 + str2;
System.out.println("Concatenated string: " + concatenatedString);
}
}
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

import java.util.Scanner;

public class StringBufferOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input for the string
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
// Create a StringBuffer object
StringBuffer stringBuffer = new StringBuffer(inputString);
// a) Find the length of the string
System.out.println("\n--- String Length ---");
System.out.println("Length of the string: " + stringBuffer.length());
// b) Reverse the string
System.out.println("\n--- Reverse String ---");
stringBuffer.reverse();
System.out.println("Reversed string: " + stringBuffer);
// Re-reverse the string to its original form for further operations
stringBuffer.reverse();
// c) Delete a substring from the given string
System.out.println("\n--- Delete Substring ---");
System.out.print("Enter the start index of the substring to delete: ");
int startIndex = scanner.nextInt();
System.out.print("Enter the end index of the substring to delete: ");
int endIndex = scanner.nextInt();
if (startIndex >= 0 && endIndex <= stringBuffer.length() && startIndex <
endIndex) {
stringBuffer.delete(startIndex, endIndex);
System.out.println("String after deletion: " + stringBuffer);
} else {
System.out.println("Invalid index range.");
}
// Close the scanner
scanner.close();
}
}
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

import java.util.Scanner;

public class StringBufferOperations {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input for the string
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
// Create a StringBuffer object
StringBuffer stringBuffer = new StringBuffer(inputString);
// a) Find the length of the string
System.out.println("\n--- String Length ---");
System.out.println("Length of the string: " + stringBuffer.length());
// b) Reverse the string
System.out.println("\n--- Reverse String ---");
stringBuffer.reverse();
System.out.println("Reversed string: " + stringBuffer);
// Re-reverse the string to its original form for further operations
stringBuffer.reverse();
// c) Delete a substring from the given string
System.out.println("\n--- Delete Substring ---");
System.out.print("Enter the start index of the substring to delete: ");
int startIndex = scanner.nextInt();
System.out.print("Enter the end index of the substring to delete: ");
int endIndex = scanner.nextInt();
if (startIndex >= 0 && endIndex <= stringBuffer.length() && startIndex <
endIndex) {
stringBuffer.delete(startIndex, endIndex);
System.out.println("String after deletion: " + stringBuffer);
} else {
System.out.println("Invalid index range.");
}
// Close the scanner
scanner.close();
}
}
8. Write a java program that implements a multi-thread application that has
three threads. First thread generates random integer every 1 second and if the
value is even, second thread computes the square of the number and prints. If
the value is odd, the third thread will print the value of cube of the number.

import java.util.Random;

public class MultiThreadDemo {


public static void main(String[] args) {
Random random = new Random();
// Create threads
Thread thread1 = new Thread(() -> {
while (true) {
int number = random.nextInt(100);
System.out.println("Generated number: " + number);
if (number % 2 == 0) {
// Even number
new Thread(() -> {
int square = number * number;
System.out.println("Square of " + number + ": " + square);
}).start();
} else {
// Odd number
new Thread(() -> {
int cube = number * number * number;
System.out.println("Cube of " + number + ": " + cube);
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
}
}
9. Write a threading program which uses the same method asynchronously to
print the numbers 1 to 10 using Thread 1 and to print 90 to 100 using Thread2.

class NumberPrinter implements Runnable {


private int start;
private int end;

// Constructor to initialize the range of numbers for each thread


public NumberPrinter(int start, int end) {
this.start = start;
this.end = end;
}

// Method to print the numbers asynchronously


public void run() {
for (int i = start; i <= end; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
// Adding a small delay to simulate asynchronous execution
try {
Thread.sleep(100); // Sleep for 100 milliseconds
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}

public class AsynchronousNumberPrinter {


public static void main(String[] args) {
// Creating two Runnable instances with different number ranges
NumberPrinter printer1 = new NumberPrinter(1, 10); // Prints 1 to 10
NumberPrinter printer2 = new NumberPrinter(90, 100); // Prints 90 to 100
// Creating two threads to run the same method asynchronously
Thread thread1 = new Thread(printer1, "Thread 1");
Thread thread2 = new Thread(printer2, "Thread 2");
// Starting the threads
thread1.start();
thread2.start();
}
}
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
d) Negative Array Size Exception

import java.util.Scanner;

public class ExceptionHandlingDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// a) ArithmeticException (e.g., Division by zero)


try {
System.out.print("Enter a number to divide 100 by: ");
int divisor = scanner.nextInt();
int result = 100 / divisor;
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}

// b) NumberFormatException (e.g., Invalid number format)


try {
System.out.print("Enter a number as a string: ");
String numberStr = scanner.next();
int number = Integer.parseInt(numberStr); // Can throw
NumberFormatException
System.out.println("Parsed number: " + number);
} catch (NumberFormatException e) {
System.out.println("Error: Invalid number format. Please enter a valid
integer.");
}

// c) ArrayIndexOutOfBoundsException (e.g., Invalid array access)


try {
int[] array = { 1, 2, 3, 4, 5 };
System.out.print("Enter an index to access: ");
int index = scanner.nextInt();
System.out.println("Array element at index " + index + ": " + array[index]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: Invalid index. Please enter an index between 0 and
" + (5 - 1));
}

// d) NegativeArraySizeException (e.g., Negative array size)


try {
System.out.print("Enter a size for the array: ");
int size = scanner.nextInt();
int[] negativeArray = new int[size]; // Can throw NegativeArraySizeException
System.out.println("Array of size " + size + " created successfully.");
} catch (NegativeArraySizeException e) {
System.out.println("Error: Array size cannot be negative.");
}

// Closing the scanner


scanner.close();
}
}

You might also like