0% found this document useful (0 votes)
10 views

java lab

The document outlines a practical lab manual for Java programming at Thiruvalluvar University, Indo-American College for the academic year 2024-2025. It includes various programming exercises such as generating prime numbers, matrix multiplication, text analysis, random number generation, and string manipulation. Each exercise provides the aim, algorithm, program code, and expected output for students to follow.

Uploaded by

praksan003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

java lab

The document outlines a practical lab manual for Java programming at Thiruvalluvar University, Indo-American College for the academic year 2024-2025. It includes various programming exercises such as generating prime numbers, matrix multiplication, text analysis, random number generation, and string manipulation. Each exercise provides the aim, algorithm, program code, and expected output for students to follow.

Uploaded by

praksan003
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 67

THIRUVALLUVAR UNIVERSITY

INDO-AMERICAN COLLEGE
CHEYYAR-604 407

DEPARTMENT OF COMPUTER APPLICATIONS

JAVAJAVA
PROGRAMMING
PROGRAM LAB LAB

2024-2025

Reg. No:…………………………………………

Name:……………………………………………

Class:……………………………………………..
THIRUVALLUVAR UNIVERSITY

INDO-AMERICAN COLLEGE
CHEYYAR-604 407

DEPARTMENT OF COMPUTER APPLICATIONS

Certified to be the bona fide


fide record of practical work done
by With register number

in this department during the Academicyear2024-2025

Staff–in-charge Head of the Department

Submitted by BCA degree practical examination held on Indo-American


college Cheyyar-604407.

Examiners:

Place: 1.

DATE: 2.
S DATE TITLE PG.
NO SIGN
NO.

WRITE A JAVA PROGRAM THAT PROMPTS THE USER FOR AN


11 27.01.25 INTEGER AND THEN PRINTS OUT OF ALL THE PRIME 1
NUMBERS UPTO THAT INTEGER.

WRITE A JAVA PROGRAM TO MULTIPLY TWO GIVEN


31.01.25
5
MATRICES.
2

05.02.25 WRITE A JAVA PROGRAM THAT DISPLAYS THE NUMBER OF


CHARACTERS, LINES AND WORDS IN A TEXT
10
3

GENERATE RANDOM NUMBERS BETWEEN TWO GIVEN


07.02.25 LIMITS USING RANDOM CLASS AND PRINT MESSAGES 14
4 ACCORDING TO THE RANGE OF THE VALUE GENERATED

WRITE A PROGRAM TO DO STRING MANIPULATION USING


CHARACTER ARRAY AND PERFORM THE FOLLOWING
STRING OPERATIONS:
15.02.25 A. STRING LENGTH 18
B. FINDING A CHARACTER AT A PARTICULAR
5 POSITION
C. CONCATENATING TWO STRINGS

WRITE A PROGRAM TO PERFORM THE FOLLOWING STRING


OPERATIONS USING STRING CLASS:
17.02.25 22
6 A. STRING CONCATENATION
B. SEARCH A SUBSTRING
C. TO EXTRACT SUBSTRING FROM GIVEN STING

WRITE A PROGRAM TO PERFORM STING


OPERATIONS USING STRING BUFFER CLASS:
7 20.02.25 A. LENGTH OF A STRING 26
B. REVERSE A STRING
C. DELETE A SUBSTRING FROM THE GIVEN STRING

WRITE A JAVA PROGRAM THAT IMPLEMENTS A MULTI THREAD


APPLICATION THAT HAS THREEE THREADS. FIRST THREAD GENERATES
24.02.25 RANDOM INTEGER EVERY 1 SECOND AND IF THE VALUE IS 30
EVEN,SECOND THREAD COMPUTES THE SQUARE OF THE NUMBER AND
8 PRINTS. IF THE VALUE IS ODD THE THIRD THREAD WILL PRINT THE
VALUE OF CUBE OF THE NUMBER.

9 03.03.25 WRITE A THREADING PROGRAM WHICH USES THE SAME


METHOD ASYNCHRONOUSLY TO PRINT THE NUMBER 1TO10
35
USING THREAD 1 AND TO RPINT 90TO100 USING THREAD2.
WRITE A PROGRAM TO DEMONSTRATE THE USE OF THE
FOLLOWING EXCEPTIONS:
A. ARITHMETIC EXCEPTION
05.03.25 B. NUMBER FORMAT EXCEPTION 39
10 C. ARRAYINDEXOUTOFBOUNDEXCEPTION
D. NEGATIVE ARRAY SIZE EXCEPTION

WRITE A JAVA PROGRAM THAT READS ON FILE NAME


FROM THE USER,THEN DISPLAYS INFORMATION ABOUT
06.03.25 42
11 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

WRITE A PROGRAM TO ACCEPT A TEXT AND CHANGE ITS


08.03.25 SIZE AND FONT.INCLUDE BOLD ITALIC OPTIONS.USE 46
12 FRAMES AND CONTROLS.

WRITE A JAVA PROGRAM THAT HANDLES ALL MOUSE


10.03.25 EVENTS AND SHOWA THE EVENT NAME AT THE CENTER OF 51
13 THE WINDOW WHEN A MOUSE EVENT IS FIRED.

12.03.25
CALCULATOR USE A GRID LAYOUT 55
14
13.03.25
SIMULATES A TRAFFIC LIGHT 60
15
EX.NO:1

DATE:27.01.25 PRIME NUMBER

AIM
The aim of this program is to print all the prime numbers from 2 up to the user provided input

ALGORITHM

Step1:start

Step2: Take an integer input num from the user.

Step3: Iterate through numbers starting from 2 to num.

Step4: For each number i, check if it is divisible by any number between 2 and i-1 (check divisibility).

Step5: If no number divides i (i.e., it's not divisible by any number other than 1
and itself),mark i as a prime number.

Step7:. Print all prime numbers.

Step8:Stop.

1
PROGRAM
import java.util.Scanner;
public class tm1
{
public static void main(String angl[])
{
Scanner scan = new Scanner(System.in);
System.out.println("enter a value:");
int num = scan.nextInt();
int num1=num+1;
for (int i = 2; i < num1;i++)
{
boolean prime = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0)
{
prime = false;
break;
}
}
if (prime)
{
System.out.println(i);
}
}
}
}

2
OUTPUT:

Enter a positive integer: 20


Prime numbers up to 20:
2 3 5 7 11 13 17 19

3
RESULT:

Thus the above program has been successfully executed


4
EX.NO:2
Write a Java program to multiply two given matrices.
DATE:31.01.25

AIM:

The aim of this program is to perform matrix multiplication of two user-input matrices

ALGORITHM:
Step 1:start

Step2:

 Accept the dimensions (rows and columns) of the two matrices.

 If the number of columns in the first matrix (col1) is not equal to the number of rows in
the second matrix (row2), print an error message and terminate

Step3: Take input for the elements of both matrices (matrix1 and matrix2).

Step4:

 Multiply the two matrices using nested loops:

 Iterate over each row of the first matrix (matrix1) and each
column of the second matrix (matrix2)

 For each combination of row and column, compute the dot product
(multiply corresponding elements and sum them).

 Store the result in a new matrix (result).

Step5: stop

5
PROGRAM

import java.util.Scanner;

public class matrix {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of rows for the first matrix: ");


int rows1 = scanner.nextInt();
System.out.print("Enter the number of columns for the first matrix: ");
int cols1 = scanner.nextInt();
System.out.print("Enter the number of rows for the second matrix: ");
int rows2 = scanner.nextInt();
System.out.print("Enter the number of columns for the second matrix: ");
int cols2 = scanner.nextInt();
if (cols1 != rows2) {
System.out.println("Matrix multiplication is not possible with these dimensions.");
return;
}

int[][] matrix1 = new int[rows1][cols1];


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

6
int[][] matrix2 = new int[rows2][cols2];
System.out.println("Enter elements of the second matrix:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = scanner.nextInt();
}
}
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];
}
}
}
System.out.println("Result of matrix multiplication:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols2; j++) {
System.out.print(result[i][j] + " ");
}
System.out.println();
}

scanner.close();
}
}

7
OUTPUT
Enter the number of rows for the first matrix: 2
Enter the number of columns for the first matrix: 3
Enter the number of rows for the second matrix: 3
Enter the number of columns for the second matrix: 2
Enter elements of the first matrix:
123
456
Enter elements of the second matrix:
78
9 10
11 12

Result of matrix multiplication:


58 64
139 154

8
RESULT:

Thus the above program has been successfully executed


9
EX.NO:3

Write a Java program that displays the number of characters, lines and
DATE:05.02.25 words in a text.

AIM:
Write a Java program using the number of characters, lines and word in a text

ALGORITHM:

STEP 1:start

STEP 2:Text Input

1.The program uses a Scanner to read input from the user line by line until the user types "END".

2.The input is stored in a String Builder for efficient string concatenation.

STEP 3:Text Analysis

1. Character count: It uses input Text. length() to calculate the total number of characters.

2. Line count: The text is split using split("\n") to count the number of lines.

3. Word count: The text is trimmed and split using split("\\s+") to count words (by whitespace).

STEP 4:Output

It prints out the results, including the number of characters, lines, and words.

STEP 5:Stop

10
PROGRAM

import java.util.Scanner;

public class tm3


{
public static void main(String[] args)
{

Scanner input = new Scanner(System.in);


System.out.println("enter text:");
int charactercount = 0;
int wordcount = 0;
int linecount = 0;
while (true)
{
String line = input.nextLine();
if (line.equalsIgnoreCase("exit"))
{
break;
}
charactercount += line.length();
String[] word = line.split("\\s+");
wordcount += word.length;
linecount++;
}
System.out.println("number of lines:" + linecount);
System.out.println("number of word:" + wordcount);
System.out.println("number of character:" + charactercount);
input.close();
}
}

11
OUTPUT

Enter the text:


This is a test.
Java programming is fun!
END

Analysis Result:
Number of characters: 41
Number of lines: 2
Number of words: 6

12
RESULT:

Thus the above program has been successfully executed

13
EX.NO:4 GENERATE RANDOM NUMBERS BETWEEN TWO GIVEN LIMITS USING RANDOM CLASS

AND PRINT MESSAGES ACCORDING TO THE RANGE OF THE VALUE GENERATED


DATE:07.02.25

AIM:
To writ a java program using random numbers

ALGORITHM:

STEP 1:start

STEP 2:Initialize Range Limits:

o Set the lower Limit to 1 and upper Limit to 100.

STEP 2:Create Random Number Generator:

o Instantiate a Random object to generate random numbers.

STEP 3:Generate and Classify Random Numbers:

o For each iteration (10 times in total), generate a random number between the lowerLimit
and upper Limit.
o Use conditional statements (if, else if, else) to classify the random number into one of
four ranges:
 [1, 25]
 (25, 50]
 (50, 75]
 (75, 100]

STEP 4:Print the Result:

o After determining the range, print the random number and its corresponding range.

STEP 5:Stop

14
PROGRAM

import java.util.Random;

public class randno {


public static void main(String[] args) {
int lowerLimit = 1;
int upperLimit = 100;
Random random = new Random();

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


int randomNumber = random.nextInt(upperLimit - lowerLimit + 1) + lowerLimit;

if (randomNumber <= 25)


System.out.println(randomNumber + " is in the range [1, 25]");
else if (randomNumber <= 50)
System.out.println(randomNumber + " is in the range (25, 50]");
else if (randomNumber <= 75)
System.out.println(randomNumber + " is in the range (50, 75]");
else
System.out.println(randomNumber + " is in the range (75, 100]");
}
}
}

15
OUTPUT

34 is in the range (25, 50]


74 is in the range (50, 75]
12 is in the range [1, 25]
60 is in the range (50, 75]
89 is in the range (75, 100]
15 is in the range [1, 25]
42 is in the range (25, 50]
77 is in the range (75, 100]
53 is in the range (50, 75]
26 is in the range (25, 50]

16
RESULT:

Thus the above program has been successfully executed


17
EX.NO:5 Write a program to do string manipulation using character array and perform the follow

String operations.
a.string length
b.finding a character at a particular position
DATE:15.02.25 c.concatenating two strings

AIM:
To write a java program using string manipulation

ALGORITHM:
STEP 1: start
STEP 2: Input Strings: Prompt the user to input two strings using Data Input Stream.
STEP 3: Length Calculation: Calculate the length of both strings using the length() method.
STEP 4: Character Extraction: Retrieve and display the character at a specific position (position 2)
from the first string using char At().
STEP 5: String Concatenation: Concatenate the two strings using the concat() method and display
the result.
STEP 6: Error Handling: Implement exception handling to catch potential input errors or other
exceptions.
STEP 7:Stop

18
PROGRAM:

import java.io.DataInputStream;
public class operation {
public static void main(String[] args) {
try {
DataInputStream dis = new DataInputStream(System.in);
System.out.print("Enter the first string: ");
String str1 = dis.readLine();
System.out.print("Enter the second string: ");
String str2 = dis.readLine();
int length1 = str1.length();
int length2 = str2.length();
int position = 2;
char charAtPosition = str1.charAt(position);
String x = str1.concat(str2);
System.out.println("Length of \"" + str1 + "\": " + length1);
System.out.println("Length of \"" + str2 + "\": " + length2);
System.out.println("Character at position " + position + " in \"" + str1 + "\": " +
charAtPosition);
System.out.println("Concatenated string: " + x);

} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
19
OUTPUT

Enter the first string: Hello


Enter the second string: World
Length of "Hello": 5
Length of "World": 5
Character at position 2 in "Hello": l
Concatenated string: Hello World

20
RESULT:

Thus the above program has been successfully executed

21
EX.NO:6 Write a program to perform the following String operations using string class.

.
DATE:17.02.25 a.string concatenation
b.search a substring
c.to extract substring from given string

AIM:
To write a java program using string operation

ALGORITHM:
STEP 1:start

STEP 2:input Strings:

 Prompt the user to enter the first string ( str1).


 Prompt the user to enter the second string ( str2).

STEP 3: Concatenate Strings:

 Concatenate str1 and str2 using the concat() method to form cString.

STEP 4: Substring Search:

 Ask the user to input a substring (sstr).


 Check if the first string (str1) contains this substring using the contains() method. Store the result in
sFnd (boolean).

STEP 5: Extract Substring:

 Ask the user to provide start and end indices ( sInd, eInd).
 Extract the substring from str1 using substring(sInd, eInd).

STEP 6: Display Results:

 Output the concatenated string.


 Output whether the substring is found in the first string.
 Output the extracted substring.

STEP 7:Stop

22
PROGRAM
import java.io.DataInputStream;

public class string {

public static void main(String[] args) {


try {
DataInputStream dis = new DataInputStream(System.in);
System.out.print("Enter the first string: ");
String str1 = dis.readLine();

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


String str2 = dis.readLine();
String cString = str1.concat(str2);
System.out.print("Enter the substring to search in the first string: ");
String sstr = dis.readLine();
boolean sFnd = str1.contains(sstr);
System.out.print("Enter the starting index to extract substring: ");
int sInd = Integer.parseInt(dis.readLine());
System.out.print("Enter the ending index to extract substring: ");
int eInd = Integer.parseInt(dis.readLine());
String estr = str1.substring(sInd, eInd);
System.out.println("Concatenated string: " + cString);
System.out.println("Substring '" + sstr + "' found in first string: " + sFnd);
System.out.println("Extracted substring from first string: " + estr);

} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}

23
OUTPUT

Enter the first string :Hello World


Enter the second string: !
Enter the substring to search in the first string: World
Enter the starting index to extract substring: 6
Entertheendingindextoextractsubstring:11
Concatenated string: Hello World!
Sub string' World' found in first string: true

24
RESULT

Thus the above program has been successfully executed

25
EX.NO: 7 Write a program to perform the following String operations using string buffer class.

. a.length of a string
DATE:20.02.25 b.reverse a string
c.delete a substring from the given string

AIM:
To write a java program using string buffer class

Algorithm:
STEP 1:start

STEP 2: Input the String:

 Prompt the user to input a string.


 Store the input string in a String Buffer object for mutable operations.

STEP 3: Length of String:

 Use the length() method of String Buffer to calculate the length of the string.

STEP 4: Reverse the String:

 Use the reverse() method of String Buffer to reverse the string.


 Convert the String Buffer back to a string using to String() for display.

STEP 5: Delete a Substring:


 Prompt the user to input the substring they want to delete from the string.
 Use index Of() to check if the substring exists in the string.
 If found, use delete() to remove the substring. If not found, display a message indicating the substring
does not exist.

STEP 6: Display Results:

 Display the string length, the reversed string, and the string after deletion (if the substring was found).

STEP 7:Stop

26
PROGRAM

import java.util.Scanner;

public class buffer {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");


String inputString = scanner.nextLine();

StringBuffer stringBuffer = new StringBuffer(inputString);


int lengthOfString = stringBuffer.length();
System.out.println("Length of the string: " + lengthOfString);
stringBuffer.reverse();
String reversedString = stringBuffer.toString();
System.out.println("Reversed string: " + reversedString);
System.out.print("Enter the substring to delete: ");
String substringToDelete = scanner.nextLine();
int index = stringBuffer.indexOf(substringToDelete);
if (index != -1) {
stringBuffer.delete(index, index + substringToDelete.length());
System.out.println("String after deleting '" + substringToDelete + "': " + stringBuffer);
} else {
System.out.println("Substring '" + substringToDelete + "' not found in the string.");
}

scanner.close();
}
}

27
OUTPUT

Enter a string: Hello, World!


Length of the string: 13
Reversed string: !dlroW ,olleH
Enter the substring to delete: Java
Substring 'Java' not found in the string.

28
RESULT

Thus the above program has been successfully executed

29
EX.NO: 8

DATE:24.02.25 MULTITHREAD

AIM:
To write a java program using multithread.

ALGORITHM:
STEP 1:start

STEP 2: Number Generation:

 A Number Generator class generates a random number between 0 and 99.


 Every time a number is generated, it checks if the number is even or odd.

STEP 3: Processing Even Numbers:

 If the generated number is even, the Even Processor thread processes it by calculating the square of
that number.

STEP 4:Processing Odd Numbers:

 If the generated number is odd, the Odd Processor thread processes it by calculating the cube of that
number.

STEP 5:Threads:

 The program runs three threads:


o The Number Generator thread keeps generating random numbers.
o The Even Processor thread processes even numbers.
o The Odd Processor thread processes odd numbers.

STEP 6:Stop

30
PROGRAM:

import java.util.Random;

class RandomNumberThread extends Thread {


public void run() {
Random = new Random();
for (int i = 0; i < 10; i++) {
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
if((randomInteger%2) == 0) {
SquareThread sThread = new SquareThread(randomInteger);
sThread.start();
}
else {
CubeThread cThread = new CubeThread(randomInteger);
cThread.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}

class SquareThread extends Thread {


int number;

SquareThread(int randomNumbern) {
number = randomNumbern;
}

public void run() {


System.out.println("Square of " + number + " = " + number * number);
}
}

class CubeThread extends Thread {


31
int number;

CubeThread(int randomNumber) {
number = randomNumber;
}

public void run() {


System.out.println("Cube of " + number + " = " + number * number * number);
}
}

public class MultithreadingTest{


public static void main(String args[]) {
RandomNumberThread rnThread = new RandomNumberThread();
rnThread.start();
}
}

32
OUTPUT
Random Integer generated : 94

Square of 94 = 8836

Random Integer generated : 59

Cube of 59 = 205379

Random Integer generated : 24

Square of 24 = 576

Random Integer generated : 50

Square of 50 = 2500

Random Integer generated : 66

Square of 66 = 4356

Random Integer generated : 80

Square of 80 = 6400

Random Integer generated : 7

Cube of 7 = 343

Random Integer generated : 24

Square of 24 = 576

Random Integer generated : 67

Cube of 67 = 300763

Random Integer generated : 93

Cube of 93 = 804357.

33
RESULT

Thus the above program has been successfully executed


34
EX.NO: 9 THREADING PROGRAM
DATE: 03.03.25

AIM:
To write a java program using threading program

ALGORITHM:
STEP 1:start
STEP 2: Create a Number Printer object:

 This object is responsible for printing the numbers.

STEP 3:Create two threads:

 thread1 prints numbers from 1 to 10.


 thread2 prints numbers from 90 to 100.

STEP 4:Start both threads:

 When the threads are started, they execute their respective tasks (printing numbers).

STEP 5:Inside print Numbers method:

 The method takes two arguments: start and end, which represent the range of numbers to print.
 It uses a for loop to print each number between start and end.
 A delay of 500 milliseconds is added between each print to slow down the printing process.
 The Thread. sleep(500) function is used to pause the execution for 500ms between printing
each number.

STEP 6:Stop

35
PROGRAM
public class sy {
public static void main(String[] args) {

NumberPrinter numberPrinter = new NumberPrinter();


Thread thread1 = new Thread(() -> {
numberPrinter.printNumbers(1, 10);
});
Thread thread2 = new Thread(() -> {
numberPrinter.printNumbers(90, 100);
});

thread1.start();
thread2.start();
}
}

class NumberPrinter {

public void printNumbers(int start, int end) {


for (int i = start; i <= end; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

36
OUTPUT

Thread-0: 1
Thread-1: 90
Thread-0: 2
Thread-1: 91
Thread-0: 3
Thread-1: 92
Thread-0: 4
Thread-1: 93
Thread-0: 5
Thread-1: 94
Thread-0: 6
Thread-1: 95
Thread-0: 7
Thread-1: 96
Thread-0: 8
Thread-1: 97
Thread-0: 9
Thread-1: 98
Thread-0: 10
Thread-1: 99
Thread-1: 100

37
RESULT

Thus the above program has been successfully executed

38
EX.NO: 10 EXCEPTION HANDLING
DATE: 05.03.25

AIM:
To write a java program using exception handling

ALGORITHM:
STEP 1:start

STEP 2:Divide by Zero (Arithmetic Exception):

 Try to divide 5 by 0, which will throw an Arithmetic Exception.


 The catch block will catch this exception and print a message indicating the error.

STEP 3:String to Integer Parsing (Number Format Exception):

 Try to parse the string "abc" into an integer, which will cause a Number Format Exception
because "abc" is not a valid number.
 The catch block will catch this exception and print a message.

STEP 4: Array Index Out of Bounds (Array Index Out Of Bound s Exception):

 Try to access an index of an array that doesn't exist (e.g., trying to access index 3 of an array with
only 3 elements).
 The catch block will catch this exception and print a message.

STEP 5:Negative Array Size (Negative Array Size Exception):

 Try to create an array with a negative size (e.g., new int[-3]), which will throw a Negative Array
Size Exception.
 The catch block will catch this exception and print a message.

STEP 6:Stop

39
PROGRAM
public class arithmetic {
public static void main(String[] args) {
try {
int result = 5 / 0;
System.out.println("Result of division: " + result);
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: Division by zero");
}
try {
String str = "abc";
int num = Integer.parseInt(str);
System.out.println("Parsed number: " + num);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: Invalid number format");
}

try {
int[] arr = {1, 2, 3};
System.out.println("Accessing element at index 3: " + arr[3]);
ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: Index out of bounds");
}
try {
int[] negativeArray = new int[-3];
System.out.println("Array created successfully with size: " + negativeArray.length);
} catch (NegativeArraySizeException e) {
System.out.println("NegativeArraySizeException caught: Negative array size");
}
}
}

40
OUTPUT

Arithmetic Exception caught: Division by zero


Number Format Exception caught: Invalid number format
Array Index Out Of Bounds Exception caught: Index out of bounds
Negative Array Size Exception caught: Negative array size

RESULT

Thus the above program has been successfully executed

41
EX.NO: 11 FILE HANDLING
DATE: 06.03.25

AIM:
To write a java program using file handling

Algorithm:

STEP 1:Get the filename from the user:

 Use Scanner to prompt the user to input a filename.

STEP 2: Create a File object:

 Create a File object using the provided filename.

STEP 3: Check if the file exists:

 If the file exists, proceed to gather details about the file.


 If the file does not exist, display an appropriate message.

STEP 3: Display file information:

 For existing files:


o Display whether the file is readable and writable.
o Show the absolute path of the file.
o Show the type of file (whether it's a regular file or a directory).
o Display the file's length in bytes.

STEP 4: Handle non-existent files:

 If the file doesn't exist, simply inform the user.

STEP 5: Close the scanner:

 Close the Scanner after the user input is processed to avoid resource leaks.

42
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 the filename: ");
String fileName = scanner.nextLine();
File file = new File(fileName);
if (file.exists()) {
System.out.println("File exists: Yes");
System.out.println("Filename: " + file.getName());
System.out.println("Absolute path: " + file.getAbsolutePath());
System.out.println("Readable: " + file.canRead());
System.out.println("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 if (file.isFile()) {
return "File";
} else {
return "Unknown";
}
}

43
OUTPUT

Enter the filename: myfile.txt


File exists: Yes
Filename: myfile.txt
Absolute path: C:\Users\User\Documents\myfile.txt
Readable: true
Writable: true
File type: File
File length in bytes: 1024

44
RESULT

Thus the above program has been successfully executed

45
EX.NO: 12 WRITE FROM A PROGRAM TO ACCEPT A TEXT AND

DATE: 08.03.25 CHANGES

AIM:
To write a java program using accept a text and changes

ALGORITHM:

STEP 1:Initialize the Frame:


o Create a JFrame for the main window of the application.
o Set the title, size, and close operation for the frame.
o Set the layout for the frame as Border Layout.

STEP 2:Create Text Area:

o Add a JTextArea in the center of the frame, where text will be entered or displayed.
o Set a default font (Arial, size 14) for the text area.
o Add a JScrollPane to enable scrolling functionality when text exceeds the visible area.

STEP 3:Create Control Panel:


o Add a JPanel at the top of the frame (North), which will contain controls for font size, bold, and
italic styling.
o Add a JComboBox for selecting the font size.
o Add two JCheckBox components for toggling bold and italic styles.

STEP 4:Event Handling:

o Add ActionListener to the font size combo box, bold, and italic checkboxes to respond to user
actions.
o When the user selects a font size from the dropdown, update the font size of the text area.
o When the user toggles the bold and italic checkboxes, update the font style in the text area
accordingly.

STEP 5:Apply Changes:

o When any control (font size, bold, italic) is modified, the corresponding change is applied to the
text area's font.

46
PROGRAM:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextEditor extends JFrame implements ActionListener {
private JTextArea textArea;
private JComboBox<String> fontSizeCombo;
private JCheckBox boldCheckBox;
private JCheckBox italicCheckBox;
public TextEditor() {
setTitle("TextEditor");
setSize(600, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
textArea = new JTextArea();
textArea.setFont(new Font("Arial", Font.PLAIN, 14));
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
fontSizeCombo = new JComboBox<>();
fontSizeCombo.addItem("12");
fontSizeCombo.addItem("14");
fontSizeCombo.addItem("16");
fontSizeCombo.addItem("18");
fontSizeCombo.addItem("20");
fontSizeCombo.setSelectedIndex(1);
fontSizeCombo.addActionListener(this);
controlPanel.add(new JLabel("Font Size:"));
controlPanel.add(fontSizeCombo);
boldCheckBox = new JCheckBox("Bold");
boldCheckBox.addActionListener(this);
controlPanel.add(boldCheckBox);
italicCheckBox = new JCheckBox("Italic");
italicCheckBox.addActionListener(this);
controlPanel.add(italicCheckBox);
add(controlPanel, BorderLayout.NORTH);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == fontSizeCombo) {
int fontSize = Integer.parseInt((String) fontSizeCombo.getSelectedItem());
Font currentFont = textArea.getFont();
Font newFont = new Font(currentFont.getFontName(), currentFont.getStyle(), fontSize);
textArea.setFont(newFont);

47
}
int fontStyle = Font.PLAIN;
if (boldCheckBox.isSelected()) {
fontStyle |= Font.BOLD;
}
if (italicCheckBox.isSelected()) {
fontStyle |= Font.ITALIC;
}
Font currentFont = textArea.getFont();
Font newFont = new Font(currentFont.getFontName(), fontStyle, currentFont.getSize());
textArea.setFont(newFont);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new TextEditor());
}
}
public void itemStateChanged(ItemEvent e) {
String fontName = fontChoice.getSelectedItem();
int fontSize = Integer.parseInt(sizeChoice.getSelectedItem());
int fontStyle = (boldCheckBox.getState() ? Font.BOLD : Font.PLAIN) |
(italicCheckBox.getState() ? Font.ITALIC : Font.PLAIN);
textArea.setFont(new Font(fontName, fontStyle, fontSize));
}
public static void main(String[] args) {
new FontChangerAWT();
}
}

48
OUTPUT

49
RESULT

Thus the above program has been successfully executed


50
EX.NO: 13 write a java program that handles all mouse events
DATE: 10.03.25

AIM:
To write a java program using handles all mouse events

ALGORITHM:

STEP 1: Initialize the Frame:

 Create a J Frame window titled Mouse Event Demo.


 Set the size of the frame to 400x300 pixels and set the default close operation to EXIT_ON_CLOSE.

STEP 2: Create Event Label:

 Add a J Label named event Label to the frame.


 Set the label's text to "Move mouse over the window" initially.
 Center the label within the frame and set the font to Arial, bold, size 20.

STEP 3: Add Mouse Listener:

 Add a Mouse Listener to the frame to listen for mouse events (click, press, release, enter, and exit).
 For each event (click, press, release, enter, exit), display the corresponding event name by calling the
display Event Name() method.

STEP 4: Display Event Name:

 The display Event Name() method updates the text of the eventLabel to show the name of the
mouse event triggered (e.g., "Mouse Clicked", "Mouse Entered").

STEP 5: Make the Frame Visible:

 Use set Visible(true) to display the frame and make the interface interactive.

51
PROGRAM

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MouseEventDemo extends JFrame {
private JLabel eventLabel;
public MouseEventDemo() {
setTitle("MouseEventDemo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
eventLabel = new JLabel("Move mouse over the window", JLabel.CENTER);
eventLabel.setFont(new Font("Arial", Font.BOLD, 20));
add(eventLabel, BorderLayout.CENTER);
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
displayEventName("Mouse Clicked");
}
@Override
public void mousePressed(MouseEvent e) {
displayEventName("Mouse Pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
displayEventName("Mouse Released");
}
@Override
public void mouseEntered(MouseEvent e) {
displayEventName("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e) {
displayEventName("Mouse Exited");
}
});
setVisible(true);
}
private void displayEventName(String eventName) {
eventLabel.setText(eventName);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new MouseEventDemo());
}
}

52
OUTPUT

53
RESULT

Thus the above program has been successfully executed

54
EX.NO: 14 CALCULAATOR USE A GRID LAYOUT
DATE: 12.03.25

AIM:
To write a java program calculator use a grid layout

ALGORITHM:

STEP 1: Initialize the Frame:

 Create a JFrame titled SimpleCalculator.


 Set the size of the frame to 300x400 pixels and set the default close operation to EXIT_ON_CLOSE.

STEP 2: Display Field:

 Create a JTextField named displayField to display the numbers and the result of operations.
 Set the text field to be non-editable so that the user cannot type directly, but the program will update
it with the correct numbers and results.
 Align the text to the right for proper number formatting.

STEP 3: Button Panel:

 Create a JPanel with a GridLayout of 4 rows and 4 columns to hold the calculator buttons.
 Add buttons for numbers (0-9), operations (+, -, *, /), the decimal point (.), and an equals (=) button.
 Each button will trigger an action when clicked, using an ActionListener.

STEP 4: Button Actions:

 When a number or decimal point is clicked, append it to the current text in the display field.
 When an operator (+, -, *, /) is clicked, append it to the display field.
 When the equals button (=) is clicked, evaluate the expression displayed in the text field.

STEP 5: Start the Application:

 Use SwingUtilities.invokeLater() to start the calculator on the Event Dispatch Thread (EDT).

55
PROGRAM
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Calculator extends JFrame implements ActionListener {
private JTextField displayField;
public Calculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
displayField = new JTextField();
displayField.setEditable(false); // Make it read-only
displayField.setHorizontalAlignment(JTextField.RIGHT);
add(displayField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(4, 4, 5, 5));
addButton(buttonPanel, "7");
addButton(buttonPanel, "8");
addButton(buttonPanel, "9");
addButton(buttonPanel, "/");
addButton(buttonPanel, "4");
addButton(buttonPanel, "5");
addButton(buttonPanel, "6");
addButton(buttonPanel, "*");
addButton(buttonPanel, "1");
addButton(buttonPanel, "2");
addButton(buttonPanel, "3");
addButton(buttonPanel, "-");
addButton(buttonPanel, "0");
addButton(buttonPanel, ".");
addButton(buttonPanel, "=");
addButton(buttonPanel, "+");
add(buttonPanel, BorderLayout.CENTER);

setVisible(true);
}
private void addButton(Container container, String text) {
JButton button = new JButton(text);
button.addActionListener(this); container.add(button);
}
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
if ("0123456789.".contains(command)) {
displayField.setText(displayField.getText() + command);
} else if (command.equals("+") || command.equals("-") || command.equals("*") || command.equals("/")) {
displayField.setText(displayField.getText() + " " + command + " ");
} else if (command.equals("=")) {
evaluateExpression();
56
}
}
private void evaluateExpression() {
String expression = displayField.getText();
String[] parts = expression.split(" ");

if (parts.length != 3) {
displayField.setText("Invalid expression");
return;
}
try {
double operand1 = Double.parseDouble(parts[0]);
String operator = parts[1];
double operand2 = Double.parseDouble(parts[2]);
double result = 0;
switch (operator) {
case "+":
result = operand1 + operand2;
break;
case "-":
result = operand1 - operand2;
break;
case "*":
result = operand1 * operand2;
break;
case "/":
if (operand2 == 0) {
displayField.setText("Error: Divide by zero");
return;
}
result = operand1 / operand2;
break;
default:
displayField.setText("Invalid operator");
return;
}
displayField.setText(Double.toString(result));
} catch (NumberFormatException ex) {
displayField.setText("Invalid expression");
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new Calculator());
}
}

57
OUTPUT

58
RESULT

Thus the above program has been successfully executed


59
EX.NO: 15 SIMULATES A TRAFFIC LIGHT
DATE: 13.03.25

AIM:
To write a java program using simulates a traffic light

ALGORITHM:

STEP 1:Initialize the Frame:

 Create a JFrame window titled TrafficLightSimulator.


 Set the size of the frame to 300x200 pixels and set the default close operation to EXIT_ON_CLOSE.

STEP 2: Radio Buttons for Traffic Light Colors:

 Create three JRadioButton objects for the colors: Red, Yellow, and Green.
 Group the radio buttons into a ButtonGroup to ensure that only one radio button can be selected at a
time.

STEP 3: ActionListener for Radio Buttons:

 Add an ActionListener to each radio button to listen for changes in the selection.
 Based on which radio button is selected, update the message displayed in the JLabel.

STEP 4: Message Panel:

 Create a JPanel to hold the message and add a JLabel to display the traffic light message.
 The message displayed in the label will change based on the selected radio button.

STEP 5: Layout and Visibility:

 Add the radio buttons panel (radioPanel) and the message panel (messagePanel) to the frame
using BorderLayout.
 Make the frame visible.

STEP 6: Handle User Interaction:


 When the user selects a radio button:
o Red: Set the label to "Stop" and the text color to red.
o Yellow: Set the label to "Ready" and the text color to yellow (darker shade).

60
PROGRAM
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TrafficLightSimulator extends JFrame implements ActionListener {
private JLabel messageLabel;
private JRadioButton redButton, yellowButton, greenButton;
public TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
JPanel radioPanel = new JPanel(new FlowLayout());
redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(redButton);
buttonGroup.add(yellowButton);
buttonGroup.add(greenButton);
redButton.addActionListener(this);
yellowButton.addActionListener(this);
greenButton.addActionListener(this);
radioPanel.add(redButton);
radioPanel.add(yellowButton);
radioPanel.add(greenButton);
JPanel messagePanel = new JPanel();
messagePanel.setLayout(new FlowLayout());
messageLabel = new JLabel("No message", JLabel.CENTER);
messageLabel.setFont(new Font("Arial", Font.BOLD, 20));
messagePanel.add(messageLabel);
add(radioPanel, BorderLayout.CENTER);
add(messagePanel, BorderLayout.NORTH);
setVisible(true); }
public void actionPerformed(ActionEvent e) {
if (e.getSource() == redButton) {
messageLabel.setText("Stop");
messageLabel.setForeground(Color.RED); }
else if (e.getSource() == yellowButton) {
messageLabel.setText("Ready");
messageLabel.setForeground(Color.YELLOW.darker());
} else if (e.getSource() == greenButton) {
messageLabel.setText("Go");
messageLabel.setForeground(Color.GREEN.darker()); }
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new TrafficLightSimulator());
61
OUTPUT

62
RESULT

Thus the above program has been successfully executed


63

You might also like