II CS JAVA PRATICAL PROGRAM
II CS JAVA PRATICAL PROGRAM
1 PRINT PRIME
NUMBERS UPTO
GIVEN INTEGER
2 MATRIX
MULTIPLICATION
3 DISPLAYS THE
NUMBER OF
CHARACTERS, LINES
AND WORDS IN A
TEXT
4 GENERATE RANDOM
NUMBERS USING
RANDOM CLASS
5 STRING MANIPULATION USING
CHARACTER ARRAY
7 STRING
OPERATIONS USING
STRING BUFFER
CLASS
8 IMPLEMENTING
MULTI THREADING
APPLICATION
9 THREAD SYNCHRONIZATION
10 EXCEPTION
HANDLING
11 FILE OPERATION
13 HANDLING MOUSE
EVENTS
14 JAVA SIMPLE
CALCULATOR
Aim:
To write a java program that prompts the user for an integer and then count out all prime
number upto that interger.
Algorithm:
1. Start
2. Importing the scanner class from Java.util package,which is used for reading user input .
3. In main method(main)
a. It creates a scanner object named scanner to read user input from reading user from the
console.
b. It prompts the user to enter an interger.
c. It read the integer entered an by the user and stores it in the variable “user input”.
d. It close the scanner object to release resources.
e. It print a message indurating that it print prime number upto entered integer .
f. It calls the print primes function passing the user input as an argument.
4. In is prime function
a. It takes an integer ’num’ as input and return true if the number is prime otherwise
flase.
b. If first check if the checks if the number is less than or equal to1,in which case it
return flase because prime number are greater 1
c. It then iterates from 2 to the square root of num ,checking if num is divisible by any
number in that range.If it is divisible by any number it return flase,indicating that the
number is not prime.
d. It the loop completes without finding any divisors,it return true,indicating that
number is prime.
5.Print prime function
a. If takes an integer limit as input and prints all prime number upto to that limit .
b. It iterates from 2 to the limit .
c. For each number i ,it calls the isprime function to check if isprime
6.Stop.
FLOWCHART:
CLASS DIAGRAM
Class prime
isprime
Print Prime(a)
FLOWCHART:
Main ();
Start
Display(a)
End
Display (limit)
Start
Limit=a;i=2
NO If<=
limit
yes
No
Isprime
(i)
yes
Write(i)
End
isPrime();
Start
n=i
Yes If
n==1
1
False NO
i=2
I<= NO
n/2
Yes
NO
ni.i=
=0
yes
Print (i)
return flase
End
Program:
Import java.util.*;
Enter interger:10
Prime number upto10:
2357
Result:
Thus the program has been executed successfully and the output is verified.
EX.NO:2
MATRIX MULIPLICATION
DATE:
Aim:
To write a java program to multiply two given martices .
Algorithm:
1 Start
2 Import the scanner class from java.util package for user input.
3 In main method
a. It creates a scanner object named scanner to read user input from the console.
b. It prompts the user to enter the dimension of the frist matrix (no of rows and
close).
c. It reads the dimension entered by the user and stones them in variable rows
7and colum1.
d. It call input matrix function passing rows 1 and columns 1 argument to input
the frist matrix.
e. If prompts the user to entered the dimension the second matrix(number of
rows and columns)
f. If read the dimension enter by the user and stores them in variable rows 2 and
columns 2.
g. It calls input matrix function passing rows 2 as argument to input the second
matrix.
h. If check if matrix muplication is possible by comparing the number of
columns of the frist matrix with the row of the second matrix .
i. If muplication is possible ,it calls the multiply matrix function passing the
two matrices as arguments and
Store the result .
j. It display the resultant matrix if multiplication is possible otherwise,if prints
a message indicating that matrix mulplication is not possible
k. It closes the scanner object to avoid resource leak.
4 input matrix function
a. It takes the number of rows and columns as input.
b. It prompts the user to enter the elements of the matrix row of row .
c. It reads the elements entered by the user and stores then in the matrix .
d. It return the matrix.
5. In multiply matrices function
a. This function takes two matrices as input.
b. If initializes a result matrix with dimension based on the number of rows of
the frist matrix and the number of columns of the second matrix .
6. In display matrix function ,it iterates over the rows of the elements of each row
,printing them with space between elements.
7. stop
FLOWCHAT: Start
Read rows2,cols2
If cols1
1=rows Yes
2 Matrix in not possible
NO
Multiply matrices(matrix1,matrix2)
End
CLASS DIAGRAM
int rows1,cols1,rows2,cols2
Read rows1,cols1
Rows2,cols2
rows
For(int i=0;j<rows1;i++)
For(int j=0;j<cols1;j++)
For(int k=0;k<cols1;k++)
Result matrices[i][j]+matrix1[i][k]=matrix,[k][j];
Next K
K
Next j
Next i
End
Start
Read rows,cols;
For(int i=0;j<rows1;i++)
For(int j=0;j<cols1;j++)
Next j
Next i
Print rows,cols;
End
Display Matrices()
Start
Read rows,value
For(int[]rows: matrix)
For(int values:rows)
Next value
Next row
Print value
End
Program:
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the dimensions of the first matrix:");
System.out.print("Number of rows: ");
int rows1 = scanner.nextInt();
System.out.print("Number of columns: ");
int cols1 = scanner.nextInt();
int[][] matrix1 = inputMatrix(scanner, rows1, cols1);
System.out.println("Enter the dimensions of the second matrix:");
System.out.print("Number of rows: ");
int rows2 = scanner.nextInt();
System.out.print("Number of columns: ");
int cols2 = scanner.nextInt();
int[][] matrix2 = inputMatrix(scanner, rows2, cols2);
if (cols1 != rows2) {
System.out.println("Matrix multiplication is not possible");
} else {
int[][] resultMatrix = multiplyMatrices(matrix1, matrix2);
System.out.println("Resultant matrix after multiplication:");
displayMatrix(resultMatrix);
}
scanner.close();
}
static int[][] inputMatrix(Scanner scanner, int rows, int cols) {
int[][] matrix = new int[rows][cols];
System.out.println("Enter the elements of the matrix:");
for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++)
{
matrix[i][j] = scanner.nextInt();
}
}
return matrix;
}
static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2)
{
int rows1 = matrix1.length;
int cols1 = matrix1[0].length;
int rows2 = matrix2.length;
int cols2 = matrix2[0].length;
int[][] resultMatrix = 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++) {
resultMatrix[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return resultMatrix;
}
static void displayMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int value : row) {
System.out.print(value + " ");
}
System.out.println();
}
}
}
Output
Result:
Thus the program has been executed successfully and the output is verified
EX.NO:3
DISPLAY THE NUMBER OF CHARACTER,LINES AND
DATE: WORDS IN A TEXT
Aim:
To write java program that display the number the number of characters lines
and words in a text.
Algorithm:
Step1:Start.
Step2:Importing the scanner class from java.util package
which is used for reading user input.
Step3:Define the text analyzer class named text analyzes.
Step4:Implement the main method.
a. Inside the main method.
b. Inside the scanner object to take user input.
c. Display a prompt asking the user to enter some text.
d. Read the input text from the user using scanner .nextLine() and store it
in the variable input text.
e. close the scanner to present resource leak.
Step5:Implement the count characters method:
a. Create a static method named count charactes that takes a string text as
a parameter.
b. Return the length of the input text using text.length().
Step 6:Implement the countless method:
a. Create a stasic method named countless that makes takes a string text
as a parameter.
b. Split the input text into an array of lines using the regular
expression\r||n||r|\n\
c. Return the length of the resulting array.
Step.7: Implement the count words method:
a. Create a static method name count the word that take as a string text
as a parameter.
b. split the input text into an array of words using the regular expression
"3+(matchas and or more white-space charlatters)
c. Return the lenght of the resulting array.
Step 8:display the analysis result:
a. a)print the analysis result to console in the main method.
b. display the number of character words and lines
step 9:stop
CLASS DIAGRAM:
intClass Text
int a,b,c,d,e,f
int character()
int lines()
int words()
FLOW CHART
Start
Read input a
d=character()
e=lines()
f=words
Print number of
character
Print number of
lines
Print number of
words
End
Characters(input a)
Start
Print
a.length()
End
Words(input a)
Start
Print
a.length()
End
Lines(input a)
Start
B=b.split()
Print
b.length()
End
Program:
import java.util.Scanner;
public class Text {
static int characters(String a) {
return a.length();
}
static int Lines(String a) {
String[] lines = a.split("\r\n|\r|\n");
return lines.length;
}
static int Words(String a) {
String[] Words = a.split("\\s+");
return Words.length;
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter some text:");
String inputText = s.nextLine();
int d = characters(inputText);
int e = Lines(inputText);
int f = Words(inputText);
System.out.println("\nAnalysis Result:");
System.out.println("Number of characters: " + d);
System.out.println("Number of lines: " + e);
System.out.println("Number of words: " + f);
}
OUTPUT
Enter some text:
java programing
Analysis Result:
Number of characters: 15
Number of lines: 1
Number of words: 2
Result:
Thus the program has been executed successfully and the output is verified.
EX.NO:4
GENERATE RANDOM NUMBERS USING RANDOM CLASS
DATE:
Aim:
To write a java program to generate random number between two given limit using
random class
Algorithm:
Step1:start
Step 2:Define the class named Random Generator.
Step 3:Declare variables lowerlimit and upperlimit to set the range far random
number generation.
Step 4: Create a random object as an instance of the random class to generate
random numbers.
Step 5: Grenerate a random number within the specified range.
a) use the nextInt method of the random class to generate a random
integer within the specified range (upper limit and lower limit) and add lower
limit to ensure it falls within the desired range.
b) Store the generated random number in the variable ran Num
Step 6 : print generated random number
Step7: Check the range of the generated number and print message accordingly.
a) use conditional statement (if, else, if and else )to check the range of
generated number
b) Print message based on the condition
i) If the number is less than 20
If the number is between 20 and 30(inclusive).
ii) If the number is greater than 30
Step 8: Stop.
Flowchart
Start
lower=10;
upper=20;
n=(upper=lower)+lower
Print n
If yes
n<=20; The generated number
is less than 20.
no
If
n>=20
&& yes The generated number
is less than 20.
n<=30
no
The generated number
is less than 20.
End
Program:
import java.util.Random;
public class RanNumGenerator {
public static void main(String[] args) {
int lower = 10;
int upper = 50; than 20.");
Random r = new Random();
int n = r.nextInt(upper - lower + 1) + lower;
System.out.println("Generated Random Number: " + n);
if (n < 20) {
System.out.println("The generated number is less
}
else if (n >= 20 && n <= 30) {
System.out.println("The generated number is between 20 and
30(inclusive).");
}
else {
System.out.println("The generated number is greater than 30.");
}
}
Output
Generated Random Number: 39
The generated number is greater than 30.
Result:
Thus the program has been executed successfully and the output is verified.
EX.NO:5
STRING MANIPULATION USING CHARACTER ARRAY
DATE:
Aim:
To perform string manipulating using character array.
Alogrimth:
Step1:Start
Step2:Declare and initialize two character array str 1and str2 with the value
“Hello” and “world”,respectively.
Step3:String length:
a. use the length properthy of the character arrays(str.1 length and str 2 length)
to find the length of each string.
b. Print the length of both string.
Step4:character at a particular position:
a. Specify a position(0-base index )as positive=2.
b. Access the character at the specified position in str.1 using array indexing
and store it in the variable char at specified
c. Print the character at specified position in string 1.
Step 5: concentrating two string.
a. Create a new character array result with a length equal to the length str1 and
str2.
b. System array copy to copy the constent of str1 to the beginning of result.
c. Use system array.copy again to consentrate the constent of str 2 to the end of
result .
d. Convert the resulting character array result to a string using new string
(result).
e. Print the concentenated string.
Step 6:Stop.
Class diagram:
Class Manipulation
int l1,l2,s1,s2
int p
Start
S1=Hello
S2=world;
L1=s1.length;
L2=s2.length;
Print l1
Print l2
P=2
Charactposition=s1[p];
Print
charatpositition
Result =char[l1+l2]
Print result
End
Program:
STRING MANIPULATION
*********************
String1 length: 5
String2 length: 5
Character at position 2 in String 1: l
Concatenated string: helloWorld
Result:
Thus the program has been executed successfully and the output is verified.
EX.NO:6
STRING OPERATIONS STRING CLASS
DATE:
Aim:
To write a java program to perform string operation using string class
Algorithm:
1) Start
2) Import the scanner class to read input from the user.
3) Define a class named string operations.
4) Inside the main method create a scanner object to read user input.
5) String concatenation.
6) Prompt the user to enter the frist string for concatenation.
7) Read the frist string using scanner nextLine().
8) Prompt the user to enter the second string.
9) Read the main string using scanner nextLine().
10)Prompt the user the enter the substring to substring to search.
11)Read the following using scanner.nextLine().
12)use the contains method to check if the main string contain the main
string contains the substring.
13)String print whether the substring is found or not.
14)Extract substring.
15)Prompt the user to enter the main string for substring extraction.
16) Read the main string using scanner .nextLine().
17)Prompt the user to enter the starting index for substring extraction.
18)Read the starting index using scanner.nextLine().
19) Prompt the user to enter the ending index for substring extracting.
20)Read theending index using scanner nextInt().
21)Use the substring method to extract the substring from the main
string basedon the specified indices.
22)Close the scanner to relase system resource.
23)Stop.
Class Diagram:
Class str
String s1,s2,s3,s4,s5,s6.
Flow Chart:
Start
Read s1,s2
S3=s1.concat(s2)
Print s2
Read s3,s4
S3..contain(s4)=s5
S6=s1.substring(start,end)
Print s6
End
Program.
import java.util.*;
public class str {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter the first string:");
String s1 = s.nextLine();
System.out.println("Enter the second string:");
String s2 = s.nextLine();
String s3 = s1.concat(s2);
System.out.println("Concatenated String: " + s3);
System.out.println("Main string: " + s1);
System.out.println("Enter the substring:");
String s4 = s.nextLine();
boolean s5 = s3.contains(s4);
System.out.println("Substring found? " + s5);
System.out.println("Main string for substring extraction: " + s1);
System.out.println("Enter the starting index:");
int start = s.nextInt();
System.out.println("Enter the ending index:");
int end = s.nextInt();
String s6 = s1.s4(start, end);
System.out.println("Extracted Substring: " + s6);
s.close();
}
}
Output:
Enter the first string:
java
Enter the second string:
programming
Concatenated String: javaprogramming
Main string: java
Enter the substring:
av
Substring found? true
Main string for substring extraction: java
Enter the starting index:
1
Enter the ending index:
4
Extracted Substring: ava
Result:
Thus the program has been executed successfully and the output is verified.
EX.NO:7
STRING OPERATIONS USING
DATE:
STRINGBUFFER
Aim:
To write a java program using operation using string buffer class .
Algorithm:
1) Start.
2) Import the java util scanner class to take user input.
3) Define the maniclass stringbuffer operations by defining the class
named stringbuffer operations.
4) Inside the main method
a. Create a scanner object (scanner)the read input from the user.
b. Read the input string using scanner.nextline()&store it in input
string.
c. Create a stringbuffer object (stringbuffer)using the input string.
d. Calculate and print the length of the string buffer.length().
e. Reverse the string using buffer.reverse().
f. Print the reversed string.
g. Create another string buffer object (string buffer) with the same
input string.
h. Prompt the user to input a substring to delete.
i. Read the substring to delete using scanner nextLine()&store it is in
substring to delete.
j. Find the index of the substring in the originally string using
stringbuffer index of(substring to delete)
k. Print the string buffer deleting the substring .
l. Close the scanner using scanner.close.
5)Stop.
Class diagram
Class str
String s1,s2,s3,s4,s5,s6.
FLOW CHART:
Start
Read input
Length=sb.length()
sb.reverse()
Start =sb1.indev(s1)
If True
Flase start!=-
1
Result:
Thus the program has been executed successfully and the output is verified.
EX.NO:8
IMPLEMENTING MULTI-THREAD APPLICATION
DATE:
Aim:
To write a Java Program that implements a multi-theread application.
Algorithm:
Step-1: Start
Step-2: Define the main class named multi-thread application.
Step-3:Inside the main method.
a) Create an instance of the shared data class (shared data) to hold generated random
number.
b) Create three threads random number Generator Square calculatar cube calculator.
c) start the three threads (random Number Generatar, start(), square calculator start ()).
Step-4: Thread 1: Shared data class. Define a class named normal name shared data to hold the
generated random Number.
a) Overside a the run method in the shared data using shared data, setrandom Number
(random Number) Handle imtempted.
Step-5:Square calculator (square calculation):
a) Implement class square calculator that implements the rurnnable interface.
b) Oversides the run method. infinite loop checking if the generated number is even -if even
complete and point the square of the number - Handle interrupted exception.
Step-6: Thread 3: Cube calculator (cube calculation)
a) Implement a class cube calculator that implements the runnable interface.
Step-7: Stop.
Class Diagram.
Main()
Start
RandomNumberGenerator.start ()
square calculator.start()
Create cube calculator ()
Create RandomNumberGenerator ()
Create square calculator()
Create cube calculator ()
End
SharedData()
Start
End
Runnable()
Initialize shared data
try
While
try?
Print RandomNumber
Catch(interrupted exception)
End
square calculation()
Start
Runnable()
run()
try
While
try?
True
If Flase
random
number%
2=100
End
Cube calculation()
Start
Runnable()
Initialize sharedData
run()
try
While
try?
True
If Flase
random
number%
Sleep(1000)
2=100
End
Program:
import java.util.Random;
public class MultiThread {
public static void main(String[] args) {
SharedData sharedData = new SharedData();
Thread randomNumberGenerator = new Thread(new
RandomNumberGenerator(sharedData));
Thread squareCalculator = new Thread(new SquareCalculator(sharedData));
Thread cubeCalculator = new Thread(new CubeCalculator(sharedData));
randomNumberGenerator.start();
squareCalculator.start();
cubeCalculator.start();
}
}
class SharedData {
private int randomNumber;
public synchronized void setRandomNumber(int randomNumber) {
this.randomNumber = randomNumber;
}
public synchronized int getRandomNumber() {
return randomNumber;
}
}
class RandomNumberGenerator implements Runnable {
private SharedData sharedData;
private Random random;
public RandomNumberGenerator(SharedData sharedData) {
this.sharedData = sharedData;
this.random = new Random();
}
public void run() {
try {
while (true) {
Thread.sleep(1000);
int randomNumber = random.nextInt(100);
System.out.println("Generated random number: " + randomNumber);
sharedData.setRandomNumber(randomNumber);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class SquareCalculator implements Runnable {
private SharedData sharedData;
public SquareCalculator(SharedData sharedData) {
this.sharedData = sharedData;
}
public void run() {
try {
while (true) {
int randomNumber = sharedData.getRandomNumber();
if (randomNumber % 2 == 0) {
int square = randomNumber * randomNumber;
System.out.println("Square of " + randomNumber + ": " + square);
}
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class CubeCalculator implements Runnable {
private SharedData sharedData;
public CubeCalculator(SharedData sharedData) {
this.sharedData = sharedData;
}
public void run() {
try {
while (true) {
int randomNumber = sharedData.getRandomNumber();
if (randomNumber % 2 != 0) {
int cube = randomNumber * randomNumber * randomNumber;
System.out.println("Cube of " + randomNumber + ": " + cube);
}
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Output:
Generated number: 23
Cube of 23 is: 12167
Generated number: 44
Square of 44 is: 1936
Generated number: 67
Cube of 67 is: 300763
Generated number: 8
Square of 8 is: 64
Generated number: 17
Cube of 17 is: 4913
Generated number: 92
Square of 92 is: 8464
Result:
Thus the program has been executed successfully and the output is verified
EX.NO:9
THREAD SYNCHRONIZATION
DATE:
Aim:
To write a Java thread program with which the Same method a sychronuntion to
Print the numbers 1 to 10 using Thread 1 and to print 90 to 100 using Thread 2.
Algorithm:
1. Start.
2. In main class create instance of the shared Data class and the threads .
3.start the threads
4: In shared variable data class (shared data) declare a private integer variable to
share the random number and Synchronized methods for accessing the random
number.
i) Set Random Number();set Random Number
ii) GetRandom Number()getRandom Number
5.In random Numbers generator Thread,accepts a shared data instance
initialized a Random of object.
6 .In a Square calculator thread (square calculator),accepts a Shared Data instance.
ⅰ) In run method, if the random number is even Complete and Print the square
of the random number
ii)Sleep for I second.
7: In Case of the cube thread (cube calculator) accepts a Shared data instance.
i)IF the random number is odd, Compute print the cube of the random number.
ii) Sleep for I second.
8: Stop.
Class();
Class :Asynchoronous Threadprinting
int i
Start
thread 1,start()
thread 2,start()
End
Thread1.run()
Start
Print
Number(1,10)
Stop
Thread2.run()
Start
Print
Number(90,100)
Stop
Print number(start,end)
Start
Read ie=Start
i<=end
Flase i=i+1
True
Flase
End
Program:
public class NumberPrinting {
public static void main(String[] args) {
Thread thread1 = new Thread(new PrintNumbers(1, 10));
Thread thread2 = new Thread(new PrintNumbers(90, 100));
thread1.start();
thread2.start();
}
}
class PrintNumbers implements Runnable {
private int start;
private int end;
public PrintNumbers(int start, int end) {
this.start = start;
this.end = end;
}
public void run() {
for (int i = start; i <= end; i++) {
System.out.println("Thread " + Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
Thread Thread-0: 1
Thread Thread-1: 90
Thread Thread-0: 2
Thread Thread-1: 91
Thread Thread-0: 3
Thread Thread-1: 92
Thread Thread-0: 4
Thread Thread-1: 93
Thread Thread-1: 94
Thread Thread-0: 5
Thread Thread-1: 95
Thread Thread-0: 6
Thread Thread-1: 96
Thread Thread-0: 7
Thread Thread-1: 97
Thread Thread-0: 8
Thread Thread-1: 98
Thread Thread-0: 9
Thread Thread-0: 10
Thread Thread-1: 99
Thread Thread-1: 100
Result:
Thus the program has been executed successfully and the output is verified.
EX.NO:10
EXCEPTION HANDLING
DATE:
Aim:
To write a java Program to demonstrate the use of exception.
Algorithm:
1. Start.
2. In main class [Exception Demo].
a) Open a Scanner to take userInput.
b) Demonstrate arithmetic exception.
ⅰ) Case divide by zero() method is a try block.
ii) If an arithmetic exception occurs catch it and Print the error message.
c) Demonstrate numbers Format exception
i) Case phrase Int form string () method in a try block.
ii) In a number format exception occurs, Catch it and print the error
message.
d) Demonstrate array indexed of bounds.
Eruptions:
ⅰ) Case access array out of bound () method in try block.
ⅱ) If an array and of bound exception occurs, catch if and print the error
message.
e) Demonstrate negative array size exception.
i) call Case create negative array() method in try block.
f) close the scanner:
* In divisible by zero method, declare numerators as 10 and demonstrate as o
and return the result of the division.
i) prompt the user to enter a number.
ⅱ) Read the input using scanner and pair it to an integer.
ⅲ) Retarn the passed integer.
ⅰ) Declare the array util elements [1, 2, 3].
ii) Try to access the element at index3 Coursing an array index of bounds
exceptions.
* In create negative array method create array with a negative size.
i) Read the input using scanner and attend to create an array with a negative
size,causing negative array size exception.
3. stop.
Class :
Class Exception Demo
int result,number,numerator,denominator,size.
Start
Flase
True
Divide Catch Arithmetic execption
zero()
Flase
Print result
Try access ArrayoutofBound
Flase
access True
Catch ArrayoutofBound
Arrayout
execption()
ofBound
Print result
Flase
End
Divide by zero()
Start
Read numberator,denominator
Print result
End
Read input
Print integer.pauseint()
Stop
Read Array[]
Print Array[]
Stop
Start
Read size
Print size
Stop
Program:
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
int result = divideByZero();
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
try {
int number = parseIntFromString();
System.out.println("Parsed number: " + number);
} catch (NumberFormatException e) {
System.out.println("Caught NumberFormatException: " + e.getMessage());
}
try {
accessArrayOutOfBound();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught ArrayIndexOutOfBoundsException: " +
e.getMessage());
}
try {
createNegativeArray();
} catch (NegativeArraySizeException e) {
System.out.println("Caught NegativeArraySizeException: " + e.getMessage());
}
scanner.close();
}
private static int divideByZero() {
int numerator = 10;
int denominator = 0;
return numerator / denominator;
}
private static int parseIntFromString() {
System.out.print("Enter a number: ");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
return Integer.parseInt(input);
}
private static void accessArrayOutOfBound() {
int[] array = {1, 2, 3};
System.out.println("Element at index 3: " + array[3]);
ArrayIndexOutOfBoundsException
}
private static void createNegativeArray() {
System.out.print("Enter the size of the array: ");
Scanner scanner = new Scanner(System.in);
int size = scanner.nextInt();
int[] negativeArray = new int[size];
}
}
Output:
Caught ArithmeticException: / by zero
Enter a number: kj
Caught NumberFormatException: For input string: "kj"
Caught ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
Enter the size of the array: -5
Caught NegativeArraySizeException: -5
Result:
Thus the program has been executed successfully and the output is verified
EX.NO:11
FILE OPERATION
DATE:
Aim:
To write a Java Program to perform File operations.
Algorithm:
1.Start
2.Import necessary libraries as the file and scanner classes.
3. Declare a class named file info in the main method create a Scanner object to
read user input.
4. To prompt user to enter a file name use the Scanner object to read the users
input and store it in a string variable.
5. create a file object as file.
6. use the exists () method of the file class to check if the file exists.
7. If the file exists, Print the following information.
*”File excists: yes"
*"File Path =" Followed by the absolute path of the file.
* "file is readable: "Followed by whether the file is writable.
* "file length (in bytes):" followed by the length of the file in bytes.
8.If the file does not exists, print "file exists: No"
9. close the scanner object to release System resources.
10.Define a private static method named getfile type takes vectors directory a file
object as a Parameter a a string indicating whatever it is a directory regular file.
11.Stop.
Class():
Class File info
Getfiletype(Filefile)
Flow Chart
Start
If flase
file.exists Print “file exists:No “
()
True
End
Get filetype(File file)
Start
If Flase
file.isDrir Print regular file
ectory()
True
Print file directory
Stop
Program:
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);
if (file.exists()) {
System.out.println("file exists: yes");
System.out.println("file path: " + file.getAbsolutePath());
System.out.println("file is readable: " + file.canRead());
System.out.println("file is writable: " + file.canWrite());
System.out.println("file type: " + getFileType(file));
System.out.println("file length (in bytes): " + file.length());
} else {
System.out.println("file exists: No");
}
scanner.close();
}
private static String getFileType(File file) {
if (file.isDirectory()) {
return "Directory";
} else {
return "Regular File";
}
}
}
Output:
Sample 1:File Exists
Enter file name:primenumber.txt
File exists: Yes
File path:C:\Example\File.txt
File is readable:true
File is writable:true
File type:Regular File
File length(in bytes): 1024
Result:
Thus the program has been executed successfully and the output is verified .
EX.NO:12
CUSTOMIZABLE TEXT USING FRAME AND
DATE: CONTROLS
Aim:
To write a java program to accept a teat and Changes its size and font.
Algorithm:
1. Start
2. Import required libraries such javax.swing.*java awt.*,and java.awt.event.*
3. Declare a class named textidition that extend Jframe and implements the
action Listener interface.
4. Declare instance variables.
Text area of type of type JTextArea for display and editing text.
Fontsize combBox of type Jcombo Box <String>for selecting font
sizes.
Bold checkbox of type Jcheckbox for toggling bold style.
Italic checkbox of type Jcheckbox for toggling italic style.
5. Constructor(TextEditor)
Set the title of the of the JFrame to “TextEditor”.
Set the size of the of the Frame to 500*400 pixels.
Set the default close operation to EXIT_ON_CLOSE.
6. Create JTextArea and name JScroll Pane:
Create JTextArea and textArea.
Set line unrapping and world wrapping properties of text area for the
text area.
Add the scroll pans to the center of the frame.
7. Create control Panel(Jpanel):
Create JPanel named control Panel.
Set the layout of the panel to flow layout.
8. Create components in control Panel
Create Jlabel named fontsizes labelwith “fontsize”.
Add the label to control panel.
Create a JcombBox string ,named font sizes comboxBox with font size
options.
Create a JcombBox components named bold and Italic styles.
9. Add control panel to the frame and set the visibility of the frame to true.
10. Override the action performed method frame set action listener interface.
11. Stop
Flow Chart
Start
Initializes,Jframe,JTextArea,set
,layout,size.
Stop
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FontChanger extends JFrame implements ActionListener {
private JTextArea textArea;
private JComboBox<String> fontBox;
private JComboBox<Integer> sizeBox;
private JCheckBox boldCheckBox, italicCheckBox;
public FontChanger() {
setTitle("Font Changer");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
textArea = new JTextArea(5, 30);
textArea.setFont(new Font("Serif", Font.PLAIN, 20));
add(textArea);
String[] fonts =
GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNa
mes();
fontBox = new JComboBox<>(fonts);
fontBox.setSelectedItem("Serif");
fontBox.addActionListener(this);
add(fontBox);
Integer[] sizes = {12, 14, 16, 18, 20, 24, 28, 32, 36, 40};
sizeBox = new JComboBox<>(sizes);
sizeBox.setSelectedItem(20);
sizeBox.addActionListener(this);
add(sizeBox);
boldCheckBox = new JCheckBox("Bold");
boldCheckBox.addActionListener(this);
add(boldCheckBox);
italicCheckBox = new JCheckBox("Italic");
italicCheckBox.addActionListener(this);
add(italicCheckBox);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String selectedFont = (String) fontBox.getSelectedItem();
int selectedSize = (Integer) sizeBox.getSelectedItem();
int style = Font.PLAIN;
if (boldCheckBox.isSelected()) {
style += Font.BOLD;
}
if (italicCheckBox.isSelected()) {
style += Font.ITALIC;
}
Font font = new Font(selectedFont, style, selectedSize);
textArea.setFont(font);
}
public static void main(String[] args) {
new FontChanger();
}
}
Output:
Result:
Thus the program has been executed successfully and the output is verified.
EX.NO:13
HANDLING MOUSEEVENT
DATE:
Aim:
To write a java program to handle all mouse events.
Algorithm:
1. Start
2. Import required libraries such as Javac(siwing)and java .awt.*;
3. Declare a class named mouse event demo extends JFrame.
4. Declare a private instance variable events label of type JLable
to display mouse events.
5. Constructor(mouse events demo)
Set the title of the of the JFrame to “Mouse Events Demo”.
Set the size of the of the Frame to 400*300 pixels.
Set the default close operation to EXIT_ON_CLOSE.
Create a JLabel named event label with the initial text “Event will
apper here “and add the label to the center frame using bored layout
label to the center using border layout.
6. Add a mouse listener using add mouse listener new mouse listener.
Override the following mouse events method.
Mouse clicked:Display “Mouse clicked”.
Mouse Pressed :Display “Mouse pressed”.
Mouse Released:Display “Mouse Released”.
Mouse Exited:Display “Mouse Exited”.
7. Create a private method display event an event named label as parameter
and set the text of the event label to provided event named .
8. Set the visibility of the frame to true.
9. In main method use swing utilizer invoke later to create a new instance of
mouse event demo.
10. Stop.
Flow Chart
Start
Initializes,Jframe,(setsizes,title,locati
on,etc())
Display Jframe
Stop
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MouseEventHandler extends JFrame {
private JLabel eventLabel;
public MouseEventHandler() {
setTitle("Mouse Event Handler");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
eventLabel = new JLabel("", JLabel.CENTER);
eventLabel.setFont(new Font("Arial", Font.BOLD, 24));
add(eventLabel, BorderLayout.CENTER);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
eventLabel.setText("Mouse Clicked");
}
public void mousePressed(MouseEvent e) {
eventLabel.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
eventLabel.setText("Mouse Released");
}
public void mouseEntered(MouseEvent e) {
eventLabel.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
eventLabel.setText("Mouse Exited");
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseMoved(MouseEvent e) {
eventLabel.setText("Mouse Moved");
}
public void mouseDragged(MouseEvent e) {
eventLabel.setText("Mouse Dragged");
}
});
setVisible(true);
}
public static void main(String[] args) {
new MouseEventHandler();
}
}
Output:
Result:
Thus the program has been executed successfully and the output is verified .
EX.NO:14
JAVA SIMPLE CALCULATOR
DATE:
Aim:
To write a java program that works as Simple calculator
Algorithm:
1. Start
2. Import necessary libraries
Import required libraries such as Javax .siwing. *and java .awt.*;
3. Define the Simple calculator class
Declare a class Simple calculator that extend JFrame.
Display field of type IText field to display input and result.
4. Constructor(Simple calculator)
Set the title of the of the Frame to “Simple calculator”.
Set the size of the of the Frame to 300*400 pixels.
Set the layout of the Frame to border layout.
5. Create JText-field for display inpit result.
Create a Text field named display input result.
Set the text field as non-edible.
Add the text to the north region of frame using border layout.
6. Create a button Jpanel named button panel with a layout of 4 rows and 4
columns.
7. Use a loop to create JButton component for the each label.
8. Add button panel to enter religion of the frame using border layout.
9. Define Inner class
Create a private inner class and named class button click listener that
implements the action listener.
10. Use swing utilities invoke later () to create a new instance of Simple
calculator.
11. Stop.
FLOW CHART
Start
Initializes frame
Events occurs(mouse/window)
Print component
Stop
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator extends JFrame implements ActionListener {
private JTextField display;
private JButton[] numberButtons;
private JButton addButton, subButton, mulButton, divButton, modButton,
clrButton, eqButton;
private JPanel panel;
private String operator;
private double num1, num2, result;
public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(400, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
display = new JTextField();
display.setEditable(false);
display.setFont(new Font("Arial", Font.BOLD, 24));
add(display, BorderLayout.NORTH);
numberButtons = new JButton[10];
for (int i = 0; i < 10; i++) {
numberButtons[i] = new JButton(String.valueOf(i));
numberButtons[i].addActionListener(this);
} addButton = new JButton("+");
subButton = new JButton("-");
mulButton = new JButton("*");
divButton = new JButton("/");
modButton = new JButton("%");
clrButton = new JButton("C");
eqButton = new JButton("=");
addButton.addActionListener(this);
subButton.addActionListener(this);
mulButton.addActionListener(this);
divButton.addActionListener(this);
modButton.addActionListener(this);
clrButton.addActionListener(this);
eqButton.addActionListener(this);
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4, 10, 10));
panel.add(numberButtons[1]);
panel.add(numberButtons[2]);
panel.add(numberButtons[3]);
panel.add(addButton);
panel.add(numberButtons[4]);
panel.add(numberButtons[5])
panel.add(numberButtons[6]);
panel.add(subButton);
panel.add(numberButtons[7]);
panel.add(numberButtons[8]);
panel.add(numberButtons[9]);
panel.add(mulButton);
panel.add(clrButton);
panel.add(numberButtons[0]);
panel.add(eqButton);
panel.add(divButton);
panel.add(modButton);
add(panel, BorderLayout.CENTER);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
if (e.getSource() == clrButton) {
display.setText("");
num1 = num2 = result = 0;
operator = "";
} else if (e.getSource() == addButton) {
num1 = Double.parseDouble(display.getText());
operator = "+";
display.setText("");
} else if (e.getSource() == subButton) {
num1 = Double.parseDouble(display.getText());
operator = "-";
display.setText("");
} else if (e.getSource() == mulButton) {
num1 = Double.parseDouble(display.getText());
operator = "*";
display.setText("");
} else if (e.getSource() == divButton) {
num1 = Double.parseDouble(display.getText());
operator = "/";
display.setText("");
} else if (e.getSource() == modButton) {
num1 = Double.parseDouble(display.getText());
operator = "%";
display.setText("");
} else if (e.getSource() == eqButton) {
num2 = Double.parseDouble(display.getText());
switch (operator) {
case "+":
result = num1 + num2;
break;
case "-":
result = num1 - num2;
break;
case "*":
result = num1 * num2;
break;
case "/":
if (num2 == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
result = num1 / num2;
break;
case "%":
if (num2 == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
result = num1 % num2;
break;
}
display.setText(String.valueOf(result));
} else {
for (int i = 0; i < 10; i++) {
if (e.getSource() == numberButtons[i]) {
display.setText(display.getText() + i);
}
}
}
} catch (ArithmeticException ae) {
display.setText("Error: " + ae.getMessage());
} catch (NumberFormatException nfe) {
display.setText("Invalid Input");
}
}
publicstatic void main(String[] args) {
new SimpleCalculator();
}
}
Output
Result:
Thus the program has been executed successfully and the output is verified .
EX.NO:15
JAVA TRAFFIC LIGHT SIMULATOR
DATE:
Aim:
To write a java program that simulator a traffic.
Algorithm:
1. Start
2. Import required libraries such as Javax .siwing. *and java .awt.*.
3. Declare a class named trafficligth simulator that extents Jframe.
4. Declare private instance variable.
Message label of type label to displat the text current state of
traffic light.
5. Constructor(Simple calculator)
Set the title of the of the Frame to “traffic ligth simulator”.
Set the size of the of the Frame to 300*200 pixels.
Set the layout of the Frame to border layout.
6. Create a Jlabel named message with an initial empty text and
created alignment and add the label to the north region of the
frame using border layout.
7. Create a button group named buttongroup
Add ratio button to the button group.
8. Add button panel to the frame:
Add the buttonpanel to the center region of the frame using border
layout.
9. Create a private inner class and named class button click listener
that implements the action listener interface.
Declare private instance variables for the message and color color
associated with button.
10. Set the foreyond color of message label to the associated color.
11. In main method use swing utilites invoke later() to create a new
instance of traffic light simulator.
12. Stop.
FLOW CHART
Start
Initializes,Jframe,(ssizes,title,layout
etc())
Display Jframe
Stop
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TrafficLightSimulator extends JFrame implements ActionListener {
private JRadioButton redButton, yellowButton, greenButton;
private JLabel messageLabel;
public TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
messageLabel = new JLabel("");
messageLabel.setFont(new Font("Arial", Font.BOLD, 20));
add(messageLabel);
redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");
ButtonGroup group = new ButtonGroup();
group.add(redButton);
group.add(yellowButton);
group.add(greenButton);
redButton.addActionListener(this);
yellowButton.addActionListener(this);
greenButton.addActionListener(this);
add(redButton);
add(yellowButton);
add(greenButton);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (redButton.isSelected()) {
messageLabel.setText("Stop");
messageLabel.setForeground(Color.RED);
} else if (yellowButton.isSelected()) {
messageLabel.setText("Ready");
messageLabel.setForeground(Color.ORANGE);
} else if (greenButton.isSelected()) {
messageLabel.setText("Go");
messageLabel.setForeground(Color.GREEN);
}
}
public static void main(String[] args) {
new TrafficLightSimulator();
}
}
Output:
Result:
Thus the program has been executed successfully and the output is verified.