0% found this document useful (0 votes)
60 views10 pages

Java Program

Java

Uploaded by

mahalakshmis
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
60 views10 pages

Java Program

Java

Uploaded by

mahalakshmis
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 10

1.

Write a Java program that prompts the user for an integer and prints all the prime numbers
upto 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 n = scanner.nextInt();
scanner.close();

System.out.println("Prime numbers up to " + n + ":");


for (int i = 2; i <= n; 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 given 2 matrices.
import java.util.Scanner;

public class MatrixMultiplication {


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

// Input dimensions of the first matrix


System.out.print("Enter the number of rows of the first matrix: ");
int rows1 = scanner.nextInt();
System.out.print("Enter the number of columns of the first matrix: ");
int cols1 = scanner.nextInt();

// Input dimensions of the second matrix


System.out.print("Enter the number of rows of the second matrix: ");
int rows2 = scanner.nextInt();
System.out.print("Enter the number of columns of the second matrix: ");
int cols2 = scanner.nextInt();

// Check if multiplication is possible


if (cols1 != rows2) {
System.out.println("Matrix multiplication is not possible with these dimensions.");
scanner.close();
return;
}

// Input the first matrix


int[][] matrix1 = new int[rows1][cols1];
System.out.println("Enter the elements of the first matrix:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i][j] = scanner.nextInt();
}
}

// Input the second matrix


int[][] matrix2 = new int[rows2][cols2];
System.out.println("Enter the elements of the second matrix:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

scanner.close();

// Multiply the matrices


int[][] result = new int[rows1][cols2];
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];
}
}
}

// Output the 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 number of characters, lines and words in a text
import java.util.Scanner;

public class TextStatistics {


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

System.out.println("Enter the text (type 'END' on a new line to finish):");


StringBuilder text = new StringBuilder();
String line;

while (!(line = scanner.nextLine()).equals("END")) {


text.append(line).append("\n");
}

scanner.close();

String inputText = text.toString();


int numberOfCharacters = inputText.length();
int numberOfLines = inputText.split("\r\n|\r|\n").length;
int numberOfWords = inputText.split("\\s+").length;

System.out.println("Number of characters: " + numberOfCharacters);


System.out.println("Number of lines: " + numberOfLines);
System.out.println("Number of words: " + numberOfWords);
}
}

4. Generate random numbers between two given limits using Random class and print messages
according to the range of value generated
import java.util.Random;
import java.util.Scanner;

public class RandomNumberGenerator {


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

// Prompt the user to enter the lower and upper limits


System.out.print("Enter the lower limit: ");
int lowerLimit = scanner.nextInt();

System.out.print("Enter the upper limit: ");


int upperLimit = scanner.nextInt();

scanner.close();
// Generate a random number between lowerLimit (inclusive) and upperLimit (inclusive)
Random random = new Random();
int randomNumber = random.nextInt(upperLimit - lowerLimit + 1) + lowerLimit;

// Print the generated random number


System.out.println("Generated Random Number: " + randomNumber);

// Print messages according to the range of the generated value


if (randomNumber < lowerLimit + (upperLimit - lowerLimit) / 3) {
System.out.println("The number is in the lower third of the range.");
} else if (randomNumber < lowerLimit + 2 * (upperLimit - lowerLimit) / 3) {
System.out.println("The number is in the middle third of the range.");
} else {
System.out.println("The number is in the upper third of the range.");
}
}
}

5. Write a program to do String manipulation using character array and perform the following
operations i) string length ii) Finding a character at a particular position iii) concatenating two
strings
import java.util.Scanner;

public class StringManipulation {


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

// Input first string


System.out.print("Enter the first string: ");
String str1 = scanner.nextLine();
char[] charArray1 = str1.toCharArray();

// Input second string


System.out.print("Enter the second string: ");
String str2 = scanner.nextLine();
char[] charArray2 = str2.toCharArray();

// i) Finding string length


int length1 = stringLength(charArray1);
int length2 = stringLength(charArray2);
System.out.println("Length of the first string: " + length1);
System.out.println("Length of the second string: " + length2);

// ii) Finding a character at a particular position


System.out.print("Enter the position to find the character in the first string: ");
int position = scanner.nextInt();
if (position >= 0 && position < length1) {
char character = charAtPosition(charArray1, position);
System.out.println("Character at position " + position + " in the first string: " +
character);
} else {
System.out.println("Position out of bounds.");
}

// iii) Concatenating two strings


char[] concatenatedArray = concatenateStrings(charArray1, charArray2);
String concatenatedString = new String(concatenatedArray);
System.out.println("Concatenated string: " + concatenatedString);

scanner.close();
}

// Method to find the length of a character array


public static int stringLength(char[] charArray) {
int length = 0;
for (char c : charArray) {
length++;
}
return length;
}

// Method to find the character at a particular position


public static char charAtPosition(char[] charArray, int position) {
return charArray[position];
}

// Method to concatenate two character arrays


public static char[] concatenateStrings(char[] charArray1, char[] charArray2) {
int length1 = charArray1.length;
int length2 = charArray2.length;
char[] result = new char[length1 + length2];

for (int i = 0; i < length1; i++) {


result[i] = charArray1[i];
}
for (int i = 0; i < length2; i++) {
result[length1 + i] = charArray2[i];
}

return result;
}
}
6. Write a program to perform the following operations using string class. i)String
concatenation ii) Search a substring iii)To extract a substring from given string
import java.util.Scanner;

public class StringOperations {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Input first string

System.out.print("Enter the first string: ");

String str1 = scanner.nextLine();

// Input second string

System.out.print("Enter the second string: ");

String str2 = scanner.nextLine();

// i) String concatenation

String concatenatedString = str1 + str2;

System.out.println("Concatenated string: " + concatenatedString);

// ii) Search a substring

System.out.print("Enter the substring to search in the first string: ");

String substring = scanner.nextLine();

if (str1.contains(substring)) {

System.out.println("The substring \"" + substring + "\" is found in the first string.");

} else {

System.out.println("The substring \"" + substring + "\" is not found in the first string.");

// iii) To extract a substring from a given string

System.out.print("Enter the starting index for substring extraction: ");

int startIndex = scanner.nextInt();

System.out.print("Enter the ending index for substring extraction: ");


int endIndex = scanner.nextInt();

if (startIndex >= 0 && endIndex <= str1.length() && startIndex < endIndex) {

String extractedSubstring = str1.substring(startIndex, endIndex);

System.out.println("Extracted substring: " + extractedSubstring);

} else {

System.out.println("Invalid indices for substring extraction.");

scanner.close();

7. Write a program to perform the following string operations using StringBuffer Class i)Length
of string ii) Reverse a string iii)Delete the 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 string
System.out.print("Enter a string: ");
String inputString = scanner.nextLine();
StringBuffer stringBuffer = new StringBuffer(inputString);

// i) Length of string
int length = stringBuffer.length();
System.out.println("Length of the string: " + length);

// ii) Reverse a string


stringBuffer.reverse();
System.out.println("Reversed string: " + stringBuffer.toString());

// Restore the original string by reversing it again


stringBuffer.reverse();

// iii) Delete a substring from the given string


System.out.print("Enter the start index for deletion: ");
int startIndex = scanner.nextInt();
System.out.print("Enter the end index for deletion: ");
int endIndex = scanner.nextInt();
if (startIndex >= 0 && endIndex <= stringBuffer.length() && startIndex < endIndex) {
stringBuffer.delete(startIndex, endIndex);
System.out.println("String after deletion: " + stringBuffer.toString());
} else {
System.out.println("Invalid indices for deletion.");
}

scanner.close();
}
}

8. Write a program that implements 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 third thread computes the
cube of the number and prints.
import java.util.Random;

class NumberGenerator extends Thread {


private int number;
private final Object lock;

public NumberGenerator(Object lock) {


this.lock = lock;
}

public void run() {


Random random = new Random();
while (true) {
number = random.nextInt(100); // Generate random number between 0 and 99
synchronized (lock) {
lock.notifyAll();
}
try {
Thread.sleep(1000); // Sleep for 1 second
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public int getNumber() {


return number;
}
}

class EvenNumberProcessor extends Thread {


private final NumberGenerator generator;
private final Object lock;

public EvenNumberProcessor(NumberGenerator generator, Object lock) {


this.generator = generator;
this.lock = lock;
}

public void run() {


while (true) {
synchronized (lock) {
try {
lock.wait();
int number = generator.getNumber();
if (number % 2 == 0) {
System.out.println("Square of " + number + " is " + (number * number));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

class OddNumberProcessor extends Thread {


private final NumberGenerator generator;
private final Object lock;

public OddNumberProcessor(NumberGenerator generator, Object lock) {


this.generator = generator;
this.lock = lock;
}

public void run() {


while (true) {
synchronized (lock) {
try {
lock.wait();
int number = generator.getNumber();
if (number % 2 != 0) {
System.out.println("Cube of " + number + " is " + (number * number *
number));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}

public class MultiThreadApplication {


public static void main(String[] args) {
Object lock = new Object();
NumberGenerator generator = new NumberGenerator(lock);
EvenNumberProcessor evenProcessor = new EvenNumberProcessor(generator, lock);
OddNumberProcessor oddProcessor = new OddNumberProcessor(generator, lock);

generator.start();
evenProcessor.start();
oddProcessor.start();
}
}

9.

You might also like