0% found this document useful (0 votes)
1 views21 pages

Java Program 1-10

The document outlines various Java programming exercises aimed at developing skills in different areas such as prime number generation, matrix multiplication, text analysis, random number generation, string manipulation, string operations, string buffer operations, multi-threading, exception handling, and file information retrieval. Each exercise includes an aim, algorithm, program code, and a result indicating successful execution. The exercises are designed for students at St. Theresa's Arts and Science College for Women, Tharangambadi.

Uploaded by

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

Java Program 1-10

The document outlines various Java programming exercises aimed at developing skills in different areas such as prime number generation, matrix multiplication, text analysis, random number generation, string manipulation, string operations, string buffer operations, multi-threading, exception handling, and file information retrieval. Each exercise includes an aim, algorithm, program code, and a result indicating successful execution. The exercises are designed for students at St. Theresa's Arts and Science College for Women, Tharangambadi.

Uploaded by

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

PAGE NO : 01

EX NO : 01
PRIME NUMBERS
DATE :
AIM :
To write a Java program that prompts the user for an integer and
then prints out all the prime numbers up to that Integer.
ALGORITHM :
Step 1: Take the input number from the user using a Scanner.
Step 2: Check if the number is less than 2; if true, print "Not Prime".
Step 3: Loop from 2 to the square root of the number.
Step 4: Inside the loop, check if the number is divisible by the current
value.
Step 5: If divisible, print "Not Prime" and stop.
Step 6: If the loop completes without finding divisors, print
"Prime". Step 7: Close the scanner to free resources.

PROGRAM CODE :

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 num = scanner.nextInt();
System.out.println("Prime numbers up to "+num+":");
for (int i = 2; i <= num; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(i+" ");
}
}

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


}
}

OUTPUT :

RESULT :

Thus the above Program was successfully executed and the output was
verified.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 03
EX NO : 02
MATRIX MULTIPLICATION
DATE :

AIM :

To Write a Java program to multiply two given matrices.

ALGORITHM :
Step 1: Take input for two matrices from the user (dimensions and
elements).
Step 2: Check if the number of columns in Matrix A equals the
number of rows in Matrix B.
Step 3: Create a result matrix of size (rows of Matrix A) x (columns of
Matrix B).
Step 4: Use nested loops to iterate through rows of Matrix A and
columns of Matrix B.
Step 5: Multiply elements of the corresponding row and column, and
sum them up to fill each cell in the result matrix.
Step 6: Print the result matrix.

PROGRAM CODE :

public class MatrixMultiplication


{ public static void main(String[] args)
{ int[][] matrix1 = { {1, 2}, {3, 4} };
int[][] matrix2 = { {5, 6}, {7, 8} };
int[][] result = new int[2][2];
for (int i = 0; i < 2; i++)
{ for (int j = 0; j < 2; j++)
{
result[i][j] = matrix1[i][0] * matrix2[0][j] + matrix1[i][1] *
matrix2[1][j];
}
}
System.out.println("Result:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++)
{ System.out.print(result[i][j] + "
");

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


}
System.out.println();
}
}
}

OUTPUT :

RESULT:

Thus the above Java program implementing Matrix Multiplication was


executed successfully

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


PAGE NO : 05
EX NO : 03
TEXT ANALYZER
DATE :

AIM :
To develop a Java program that displays the number of characters,
lines and words in a text.

ALGORITHM :

Step 1: Take input text from the user.


Step 2: Remove unnecessary spaces and standardize the case
(optional).
Step 3: Count the number of characters.
Step 4: Count the number of words (split text by spaces).
Step 5: Count the number of sentences (split by ., !, or ?).
Step 6: Display the analysis results to the user.

PROGRAM CODE :

public class TextAnalyzer


{
public static void main(String[] args)
{
String text = "Hello world\nJava programming is fun\nThis is a
simple program.";
int lineCount = text.split("\n").length;
int wordCount = text.split("\\s+").length;
int characterCount = text.length();
System.out.println("Number of lines: " + lineCount);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of characters: " + characterCount);
}
}

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


PAGE NO : 06

OUTPUT :

RESULT :

Thus the above Java program implementing a Text Analyzer was


executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


PAGE NO : 07
EX NO: 04

DATE : RANDOM NUMBERS

AIM :

To develop a Java program Generate random numbers between


two given limits using Random class and print messages according
to the range of the value generated.

ALGORITHM :

Step 1: Import the java.util.Random or use Math.random().


Step 2: Create a Random object (if using Random).
Step 3: Use the appropriate method to generate random numbers.
Step 4: Print or use the random numbers in your program.

PROGRAM CODE :

import java.util.Random;
public class RandomNumber {
public static void main(String[] args)
{ int lowerLimit = 10;
int upperLimit = 50;
Random random = new Random();
int randomNumber = random.nextInt(upperLimit - lowerLimit + 1) +
lowerLimit;
System.out.println("Generated number: " + randomNumber);
if (randomNumber < 20) {
System.out.println("The number is less than 20.");
} else if (randomNumber <= 35) {
System.out.println("The number is between 20 and 35.");
}

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


else {
System.out.println("The number is greater than 35.");
}
}
}

OUTPUT :

RESULT:
Thus the above Java program for generate Random numbers was
executed Successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


PAGE NO : 09
EX NO: 05
STRING MANIPULATION
DATE :

AIM :

To develop a Java program to do String Manipulation using


Character Array and perform the following string operations: String
length,Finding a character at a particular position, Concatenating two
strings.

ALGORITHM :
Step 1: Input the string using Scanner.
Step 2: Concatenate the string with another string.
Step 3: Extract a substring from the string.
Step 4: Find the length of the string.
Step 5: Access a specific character in the string.
Step 6: Replace specific characters or substrings.
Step 7: Split the string into an array of words.

PROGRAM CODE :

public class StringManipulation


{ public static void main(String[] args)
{ String str1 = "Hello";
String str2 = "World";
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
System.out.println("Length of str1: " + charArray1.length);
System.out.println("Character at position 2 in str1: " +
charArray1[2]);
char[] result = new char[charArray1.length +
charArray2.length];
System.arraycopy(charArray1, 0, result, 0, charArray1.length);
System.arraycopy(charArray2, 0, result, charArray1.length,
charArray2.length);

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


PAGE NO : 10

System.out.println("Concatenated string: " + new String(result));


}
}

OUTPUT :

RESULT :

Thus the Java programming used to implement String Manipulation


was executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 11
EX NO : 06

DATE : STRING OPERATIONS

AIM :

To develop a Java program to perform the following string operations


using String class: String Concatenation, Search a substring,To
extract substring from given string.

ALGORITHM :

Step 1: Declare two string variables str1 and str2 and initialize
them with "Hello" and "World" respectively.
Concatenate str1 and str2 with a space (" ") in between.
Step 2 : Declare a string variable searchSubstring and initialize it
with "World".Use the contains() method to check if
concatenated contains searchSubstring.
Step 3 : Print the result (either true or false).
Step 4 : Extract a Substring : Use the substring(6, 11) method
on concatenated to extract characters from index 6 to 10
(since the end index 11 is exclusive).
Step 5 : Store the extracted substring in extractedSubstring.
Step 6 : Print the Extracted Substring
Step 7 : Display the value of extractedSubstring using
System.out.println().

PROGRAM CODE :

public class StringOperations {


public static void main(String[] args)
{ String str1 = "Hello";
String str2 = "World";
String concatenated = str1 + " " + str2;
System.out.println("Concatenated String: " + concatenated);
String searchSubstring = "World";
System.out.println("Contains 'World'? : " +
concatenated.contains(searchSubstring));

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


PAGE NO : 12

String extractedSubstring = concatenated.substring(6, 11);


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

OUTPUT :

RESULT :
Thus the Java programming used to perform String Operations was
executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


PAGE NO : 13
EX NO : 07
STRING BUFFER OPERATION
DATE :

AIM :

To develop a Java program to perform string operations using


String Buffer class: Length of a string, Reverse a string, Delete a
substring from the given string.

ALGORITHM :
Step 1: Create a StringBuffer object with an initial string.
Step 2: Append a string to the existing buffer using append().
Step 3: Insert a string at a specific index using PAGE
dex, str).NO : 16
insert(in Step 4: Replace part of the string using
replace
(startIndex, endIndex, str).
Step 5: Delete part of the string using delete(startIndex, endIndex).
Step 6: Reverse the string using reverse().
Step 7: Find the length of the buffer using length().

PROGRAM CODE :

public class StringBufferOperations {


public static void main(String[] args) {
StringBuffer str = new StringBuffer("HelloWorld");
System.out.println("Length: " + str.length());
System.out.println("Reversed: " + str.reverse());
str.reverse();
str.delete(5, 10);
System.out.println("After Deletion: " + str);
}
}

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


PAGE NO : 14

OUTPUT :

RESULT :

Thus the Java program to perform String Buffer Operation was


executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


PAGE NO : 15
EX NO : 08
MULTI THREAD
DATE :

AIM :

To develop a Java program that implements a multi-thread


application.

ALGORITHM :
Step 1: Create a class that implements Runnable or extends
Thread. Step 2: Override the run() method to define the task to be
executed. Step 3: Create instances of the class for each thread.
Step 4: Start the thread using the start() method.
Step 5: Use join() if you need to wait for a thread to finish.

PROGRAM CODE :

class Thread1 extends Thread


{ public void run() {
for (int i = 1; i <= 5; i++)
{ System.out.println("Thread 1: " + i);
}
}
}
class Thread2 extends Thread
{ public void run() {
for (int i = 1; i <= 5; i++)
{ System.out.println("Thread 2: " + i);
}
}

}
public class MultiThread {
public static void main(String[] args)
{ Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
t2.start();
}
}
OUTPUT :

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


RESULT :

Thus the Java program used to implement Multi thread was executed
successfully

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


PAGE NO : 17
EX NO : 09
EXCEPTION HANDLING
DATE :

AIM :
To develop a Java program to demonstrate the use of following exceptions:
Arithmetic Exception, Number Format Exception, Array Index Out of
Bound Exception, Negative Array Size Exception.
ALGORITHM :
Step 1: Identify code that may throw exceptions.
Step 2: Wrap the risky code in a try block.
Step 3: Catch specific exceptions using catch blocks.
Step 4: Optionally, use a finally block for cleanup code.
Step 5: Use throw to manually raise an exception.
Step 6: Create custom exceptions by extending the Exception class
(if needed).
Step 7: Use throws in method signatures to declare exceptions.

PROGRAM CODE :
public class ExceptionDemo {
public static void main(String[] args)
{ try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
try {
int number = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("Caught NumberFormatException: " + e.getMessage());
}
try {
int[] array = {1, 2, 3};
int value = array[5];
} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("CaughtArrayIndexOutOfBoundsException:"+e.getMessage());

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 18

}
try {
int[] array = new int[-5];
} catch (NegativeArraySizeException e) {
System.out.println("Caught NegativeArraySizeException: " + e.getMessage());
}
}
}

OUTPUT :

RESULT :

Thus the Java programming to implement Exception Handling was


executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 19
EX NO : 10
FILE INFORMATION
DATE :

AIM :
To develop a Java program that reads on file name from the user, then
displays information about whether the file exists, whether the file is
readable, whether the file is writable, the type of file and the length of
the file in bytes.
ALGORITHM :
Step 1 : Create a Scanner object for user input.
Step 2 : Prompt the user to enter a file name.
Step 3 : Read the file name from the user.
Step 4 : Create a File object using the given file name.
Step 5 : Check if the file exists using file.exists(), and display the
result.
Step 6 : Check if the file is readable using file.canRead(), and
display the result.
Step 7 : Check if the file is writable using file.canWrite(), and
display the result.
Step 8 : Determine whether the file is a regular file or a directory
using file.isFile(), and display the result.
Step 9 : Get the file size using file.length(), and display it in bytes.

PROGRAM CODE :
import java.io.File;
import java.util.Scanner;
public class FileInfo {
public static void main(String[] args)
{ Scanner scanner = new
Scanner(System.in);
System.out.print("Enter file name: ");
String fileName = scanner.nextLine();
File file = new File(fileName);
System.out.println("File exists: " + file.exists());
System.out.println("File is readable: " + file.canRead());
System.out.println("File is writable: " + file.canWrite());

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 20

System.out.println("File type: " + (file.isFile() ?


"File" :
"
Directory"));
System.out.println("File length:
" + file.length() + "
bytes");
}
}

OUTPUT :

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 21

RESULT :

Thus the Java programming for Handling File


Information was executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI

You might also like