Java Programming Lab Manual
Java Programming Lab Manual
JAVA PROGRAMMING
2024 BATCH
(Autonomous)
JAVA PROGRAMMING – LAB MANUAL
COURSE OBJECTIVES
1. Develop a deep understanding of Java programming basics, including syntax, control
structures, and data types.
2. Learn the use of arrays, strings, and file handling for problem-solving.
3. Foster algorithmic thinking to solve mathematical, logical, and real-world problems like
prime numbers, matrix multiplication, and string operations.
4. Understand and implement Java’s multithreading features for concurrent programming.
5. Perform operations using different string-handling classes, such as String, StringBuffer,
and character arrays.
6. Work with file operations to perform data analysis, retrieve file properties, and implement
user input/output.
7. Design graphical user interfaces (GUIs) using Java Swing for applications like calculators,
traffic light simulations, and mouse event handlers.
8. Learn Java’s event-handling model to manage user interactions like mouse clicks, key
presses, and GUI controls.
COURSE OUTCOMES
1. Develop and test Java programs for basic operations, control structures, and
computational problems.
2. Solve mathematical problems like prime number detection and matrix multiplication
using efficient algorithms.
3. Use String, StringBuffer, and character arrays to perform operations like concatenation,
substring extraction, reversal, and searching.
4. Design and implement multithreaded programs to solve concurrent tasks, including
random number processing and asynchronous method execution.
5. Write robust Java programs that use exception handling for common runtime errors like
ArithmeticException, NumberFormatException, and ArrayIndexOutOfBoundsException.
6. Perform file operations to read, write, and retrieve file properties such as size, readability,
and writability.
7. Create interactive applications using Java Swing, such as calculators and traffic light
simulations, employing effective layouts and event handling.
8. Use listener interfaces and adapter classes to handle events like mouse clicks and user
actions effectively.
Objective Outcome
Strengthen Core Java Fundamentals CO1
Enhance Problem-Solving Skills CO2
Develop Multithreading and Exception Handling Skills CO4, CO5
Learn String Manipulation Techniques CO3
Master File Handling and I/O Operations CO6
Introduce GUI Programming CO7
Understand Event Handling CO8
SYLLABUS
Java program that prompts the user for an integer and then prints out all the prime
2
numbers up to that Integer.
4 Java program that displays the number of characters, lines, and words in a text.
Generate random numbers between two given limits using Random class and
5
print messages according to the value range generated.
Java program to do String Manipulation using Character Array and perform the
following string operations:
6 a) String length
b) Finding a character at a particular position
c) Concatenating two strings.
Java program to perform the following string operations using the String class:
a) String Concatenation
7 b) Search a substring
c) To extract a substring from the given.
Java program to perform string operations using the String Buffer class:
a) Length of a string
8 b) Reverse a string
c) Delete a substring from the given string.
Java program that implements a multi-thread application that has three threads.
The first thread generates a random integer every 1 second and if the value is
9 even, the second thread computes the square of the number and prints. If the
value is odd, the third thread will print the value of the cube of the number.
Threading program that uses the same method asynchronously to print the
10
numbers 1 to 10 using Thread1 and to print 90 to 100 using Thread2.
Java program will demonstrate the use of the following exceptions:
11 a) ArithmeticException
b) NumberFormatException
c) ArrayIndexOutofBoundException
d) NegativeArraySizeException.
Java program reads the file name from the user, then displays information about
12 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.
Java program to accept a text and change its size and font. Include bold italic
13 options. Use frames and controls.
Java program that handles all mouse events and shows the event name at the
14
center of the window when a mouse event is fired. (Use adapter classes).
Java program that works as a simple calculator. Use a grid layout to arrange
15 buttons for the digits and for the +, -, *, and % operations. Add a text field to
display the result. Handle any possible exceptions like divide by zero.
Java program that simulates a traffic light. The program lets the user select one
of three lights: red, yellow, or green with radio buttons. On selecting a button,
16
an appropriate message with “stop” “ready” or “go” should appear above the
buttons in a selected color. Initially, there is no message shown.
LIST OF EXPERIMENTS
Java program that displays the number of characters, lines, and words
4. 19
in a text.
Generate random numbers between two given limits using Random
5. 25
class and print messages according to the value range generated.
Java program to do String Manipulation using Character Array and
perform the following string operations:
6. a) String length 30
b) Finding a character at a particular position
c) Concatenating two strings.
Java program to perform the following string operations using
the String class:
7. a) String Concatenation 35
b) Search for a substring
c) To extract a substring from the given.
Java program to perform string operations using the String Buffer
class:
8. a) Length of a string 41
b) Reverse a string
c) Delete a substring from the given string.
Java program that implements a multi-thread application that has
three threads. The first thread generates a random integer every 1
9. second and if the value is even, the second thread computes the 46
square of the number and prints. If the value is odd, the third thread
will print the value of the cube of the number.
Threading program that uses the same method asynchronously
10. to print the numbers 1 to 10 using Thread1 and to print 90 to 55
100 using Thread2.
Java program will demonstrate the use of the following exceptions:
11. a) ArithmeticException 61
b) NumberFormatException
c) ArrayIndexOutofBoundException
d) NegativeArraySizeException.
Java program reads the file name from the user, then displays
information about whether the file exists, whether the file is readable,
12. 69
whether the file is writable, the type of file, and the length of the file
in bytes.
Java program to accept a text and change its size and font. Include
13. bold italic options. Use frames and controls. 74
Java program that handles all mouse events and shows the event
14. name at the center of the window when a mouse event is fired. (Use 82
adapter classes).
Java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -, *, and % operations.
15. 89
Add a text field to display the result. Handle any possible exceptions
like divide by zero.
Java program that simulates a traffic light. The program lets the user
select one of three lights: red, yellow, or green with radio buttons. On
16. selecting a button, an appropriate message with “stop” “ready” or 98
“go” should appear above the buttons in a selected color. Initially,
there is no message shown.
PREREQUISITES
General Knowledge Prerequisites
• Basic Syntax: Familiarity with main() method, data types, variables, operators, and
control structures (if, for, while).
• Object-Oriented Programming (OOP): Understanding classes, objects, constructors,
and basic inheritance.
• Exception Handling: Knowledge of try-catch-finally blocks and built-in Java
exceptions.
• Multithreading: Basics of threads, Thread class, and Runnable interface.
• String Handling: Familiarity with String, StringBuffer, and StringBuilder classes.
c. Event Handling
d. GUI Development
• JDK:
o Install the latest JDK (Java SE 17 or later).
o Set up environment variables (JAVA_HOME and PATH).
o Verify installation:
java -version
javac -version
c. Text Editor
• For quick programs, use simple editors like Notepad++ or Visual Studio Code.
Program-Specific Prerequisites
2. Prime Numbers
• Required Knowledge:
o Loops and conditional statements.
o Mathematical logic for prime number detection.
3. Matrix Multiplication
• Required Knowledge:
o Arrays in Java (1D and 2D).
o Nested loops for matrix operations.
• Required Knowledge:
o File I/O using FileReader or Scanner.
o String manipulation for counting words and lines.
• Tools: Basic text file for input.
5. Random Numbers
• Required Knowledge:
o Random class for generating random numbers.
o Conditional statements to handle ranges.
• Required Knowledge:
o Familiarity with String, StringBuffer, and character arrays.
o Operations like concatenation, reversing, and substring handling.
9-10. Multithreading
• Required Knowledge:
o Basics of the Thread class and Runnable interface.
o Using Thread.sleep() for delays.
o Synchronization to manage shared resources (if required).
• Required Knowledge:
o Understanding built-in exceptions like ArithmeticException,
NumberFormatException, etc.
o Using try-catch blocks for handling errors.
• Required Knowledge:
o File class for checking file properties (readable, writable, size, etc.).
• Tools: Sample file for testing.
• Required Knowledge:
o Java Swing components: JFrame, JTextField, and JButton.
o Font handling using Font class.
• Required Knowledge:
o Event handling using MouseListener and adapter classes.
o Displaying events using JLabel.
• Required Knowledge:
o Swing layout managers (e.g., GridLayout).
o Event handling for button clicks.
• Required Knowledge:
o Swing components like JRadioButton and JPanel.
o Conditional logic for handling radio button selections.
o Color manipulation using Color class.
EXPERIMENT - 1
AIM:
To write a Java program that swaps the values of two numbers without using a third variable, using
the Scanner class for input.
ALGORITHM:
Page | 1
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
SOURCE CODE:
import java.util.Scanner;
public class SwapNumbers {
public static void main(String[] args) {
int a, b;
Page | 2
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
CODE EXPLANATION:
1. import java.util.Scanner;
o Imports the Scanner class, which is used to read user input from the console.
2. public class SwapNumbers {
o Defines the class SwapNumbers, which contains the program logic.
3. public static void main(String[] args) {
o The entry point of the program. This method is executed when the program runs.
4. int a, b;
o Declares two integer variables a and b to store the numbers.
5. Scanner scanner = new Scanner(System.in);
o Creates a Scanner object to read input from the console.
6. System.out.print("Enter first number (a): ");
o Prompts the user to enter the first number.
Page | 3
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
7. a = scanner.nextInt();
o Reads an integer from the user and assigns it to the variable a.
8. System.out.print("Enter second number (b): ");
o Prompts the user to enter the second number.
9. b = scanner.nextInt();
o Reads another integer from the user and assigns it to the variable b.
10. System.out.println("\nBefore Swapping:");
o Prints a message indicating the start of the "before swapping" section.
11. System.out.println("a = " + a);
o Displays the value of a before swapping.
12. System.out.println("b = " + b);
o Displays the value of b before swapping.
13. a = a + b;
o Adds the values of a and b and stores the result in a. At this point, a holds the sum
of the two numbers.
14. b = a - b;
o Subtracts b (the original value) from a (the sum of a and b). This operation
effectively assigns the original value of a to b.
15. a = a - b;
o Subtracts the new b (which now holds the original value of a) from a (the sum of
the original a and b). This operation assigns the original value of b to a.
16. System.out.println("\nAfter Swapping:");
o Prints a message indicating the start of the "after swapping" section.
17. System.out.println("a = " + a);
o Displays the value of a after swapping.
18. System.out.println("b = " + b);
o Displays the value of b after swapping.
19. scanner.close();
o Closes the Scanner object to release system resources. It is good practice to close
the scanner after use.
Page | 4
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 5
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT - 2
AIM:
Write a Java program that prompts the user for an integer and displays all prime numbers up to
that integer.
ALGORITHM:
Page | 6
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
Page | 7
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
SOURCE CODE:
public class PrimeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int n = scanner.nextInt();
System.out.println("Prime numbers up to " + n + " are:");
for (int i = 2; i <= n; i++) {
boolean isPrime = true;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
isPrime = false; // i is not prime
break; // exit the inner loop
}
}
if (isPrime) {
System.out.print(i + " "); number
}
}
scanner.close();
}
}
CODE EXPLANATION:
Page | 8
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
Page | 9
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
18. }
o Ends the main method.
19. }
o Ends the PrimeNumbers class.
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 10
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT - 3
AIM:
Write a Java program that multiplies two matrices, taking input from the user, and then calculates
and prints the product of the matrices.
ALGORITHM:
Page | 11
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
Page | 12
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
SOURCE CODE:
import java.util.Scanner;
public class MatrixMultiplication {
public static void main(String[] args) {
Scanner myobj = new Scanner(System.in);
System.out.print("Enter the number of rows for matrix A: ");
int rowsA = myobj.nextInt();
System.out.print("Enter the number of columns for matrix A: ");
int colsA = myobj.nextInt();
System.out.print("Enter the number of rows for matrix B: ");
int rowsB = myobj.nextInt();
System.out.print("Enter the number of columns for matrix B: ");
int colsB = myobj.nextInt();
if (colsA != rowsB) {
System.out.println("Matrix multiplication is not possible.");
return;
}
int[][] a = new int[rowsA][colsA];
int[][] b = new int[rowsB][colsB];
int[][] c = new int[rowsA][colsB];
System.out.println("Enter elements of matrix A:");
for (int i = 0; i < rowsA; i++)
{
for (int j = 0; j < colsA; j++)
{
a[i][j] = myobj.nextInt();
}
}
System.out.println("Enter elements of matrix B:");
for (int i = 0; i < rowsB; i++)
{
Page | 13
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
Page | 14
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
CODE EXPLANATION:
1. import java.util.Scanner;
o Imports the Scanner class for user input.
2. public class MatrixMultiplication {
o Declares a class named MatrixMultiplication.
3. public static void main(String[] args) {
o The main method where the program execution begins.
4. Scanner myobj = new Scanner(System.in);
o Creates a Scanner object to read input from the user.
5. System.out.print("Enter the number of rows for matrix A: ");
o Prompts the user to enter the number of rows for matrix A.
6. int rowsA = myobj.nextInt();
o Reads the number of rows for matrix A and stores it in rowsA.
7. System.out.print("Enter the number of columns for matrix A: ");
o Prompts the user to enter the number of columns for matrix A.
8. int colsA = myobj.nextInt();
o Reads the number of columns for matrix A and stores it in colsA.
9. System.out.print("Enter the number of rows for matrix B: ");
o Prompts the user to enter the number of rows for matrix B.
10. int rowsB = myobj.nextInt();
o Reads the number of rows for matrix B and stores it in rowsB.
11. System.out.print("Enter the number of columns for matrix B: ");
o Prompts the user to enter the number of columns for matrix B.
12. int colsB = myobj.nextInt();
o Reads the number of columns for matrix B and stores it in colsB.
13. if (colsA != rowsB) {
o Checks if matrix multiplication is possible. The number of columns in matrix A
must equal the number of rows in matrix B.
14. System.out.println("Matrix multiplication is not possible.");
o Prints a message if matrix multiplication is not possible.
15. return;
Page | 15
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
Page | 16
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
o Multiplies the corresponding elements and adds to the result matrix at [i][j].
31. System.out.println("The product of the matrices is:");
o Prints the result matrix.
32. for (int i = 0; i < rowsA; i++) {
o Loops through each row of the result matrix.
33. for (int j = 0; j < colsB; j++) {
o Loops through each column of the result matrix.
34. System.out.print(c[i][j] + " ");
o Prints the value of the result matrix at position [i][j].
35. System.out.println();
o Moves to the next line after printing one row of the result matrix.
36. myobj.close();
o Closes the Scanner to release resources.
37. }
o Closes the main method.
38. }
o Closes the MatrixMultiplication class.
Page | 17
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 18
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT - 4
AIM:
Write a Java program that reads a text file and displays the number of characters, lines, and words
in the file.
ALGORITHM:
Page | 19
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
Page | 20
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
SOURCE CODE:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TextStatistics {
public static void main(String[] args) {
String filePath = "path/to/your/textfile.txt"; // Change to your file path
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
int characterCount = 0;
int lineCount = 0;
int wordCount = 0;
while ((line = reader.readLine()) != null) {
lineCount++;
characterCount += line.length();
wordCount += line.split("\\s+").length; // Split by whitespace
}
System.out.println("Characters: " + characterCount);
System.out.println("Lines: " + lineCount);
System.out.println("Words: " + wordCount);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Page | 21
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
CODE EXPLANATION:
import java.io.BufferedReader;
• Purpose: Imports the BufferedReader class to read text from a file efficiently, line by
line.
import java.io.FileReader;
• Purpose: Imports the FileReader class, which is used to read the contents of a file.
import java.io.IOException;
• Purpose: Imports the IOException class, which is needed to handle input-output-related
exceptions (e.g., file not found or read errors).
public class TextStatistics {
• Purpose: Declares a class named TextStatistics. This is the program's main class.
public static void main(String[] args) {
• Purpose: The main method is the entry point of the program where execution begins.
String filePath = "path/to/your/textfile.txt";
• Purpose: Defines a string variable filePath that stores the path to the text file to be
analyzed. You need to replace "path/to/your/textfile.txt" with the actual file path.
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
• Purpose:
1. Creates a BufferedReader object reader to read the file.
2. The new FileReader(filePath) reads the file at the specified path.
3. The try-with-resources ensures the BufferedReader is automatically closed after
the operations complete, preventing resource leaks.
String line;
• Purpose: Declares a variable line to store each line of text read from the file.
int characterCount = 0;
• Purpose: Initializes a variable characterCount to 0. It will store the total number of
characters in the file.
int lineCount = 0;
• Purpose: Initializes a variable lineCount to 0. It will store the total number of lines in the
file.
Page | 22
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
int wordCount = 0;
• Purpose: Initializes a variable wordCount to 0. It will store the total number of words in
the file.
while ((line = reader.readLine()) != null) {
• Purpose: Reads each line from the file until there are no more lines (null indicates the
end of the file).
• Explanation:
o reader.readLine() reads a single line of text from the file.
o The line variable stores the current line.
lineCount++;
• Purpose: Increments the lineCount by 1 for each line read, keeping track of the total
number of lines.
characterCount += line.length();
• Purpose: Adds the length of the current line to characterCount, counting all the
characters (including spaces and punctuation) in the file.
wordCount += line.split("\\s+").length;
• Purpose: Counts the words in the current line and adds them to wordCount.
• Explanation:
o line.split("\\s+") splits the line into an array of words, using one or more
whitespace characters (\\s+) as the delimiter.
o .length gets the number of elements in the array, which represents the number of
words.
}
• Purpose: Ends the while loop after processing all lines in the file.
System.out.println("Characters: " + characterCount);
• Purpose: Prints the total number of characters counted in the file.
System.out.println("Lines: " + lineCount);
• Purpose: Prints the total number of lines counted in the file.
System.out.println("Words: " + wordCount);
• Purpose: Prints the total number of words counted in the file.
Page | 23
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
} catch (IOException e) {
• Purpose: Catches any IOException that might occur during file reading (e.g., file not
found or read errors).
e.printStackTrace();
• Purpose: Prints the stack trace of the exception to the console for debugging purposes.
}
• Purpose: Ends the try-catch block
}
• Purpose: Ends the main method and the program.
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 24
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT - 5
AIM:
Generate random numbers between two given limits using Random class and print messages
according to the value range generated.
ALGORITHM:
Page | 25
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
SOURCE CODE:
import java.util.Random;
import java.util.Scanner;
public class RandomNumberGenerator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
// Input for range limits
System.out.print("Enter the lower limit: ");
Page | 26
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
CODE EXPLANATION:
1. import java.util.Random;
This imports the Random class, which is used for generating random numbers.
2. import java.util.Scanner;
This imports the Scanner class, which is used for reading user input from the console.
3. public class RandomNumberGenerator {
Declares the class named RandomNumberGenerator.
4. public static void main(String[] args) {
Defines the main method, which is the starting point of the program.
5. Scanner scanner = new Scanner(System.in);
Creates a Scanner object to take user input from the console.
Page | 27
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
Page | 28
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
21. }
Closes the if-else block.
22. }
Closes the main method.
23. }
Closes the class definition.
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 29
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT - 6
AIM:
Java program to do String Manipulation using CharacterArray and perform the following string
operations.
ALGORITHM:
Page | 30
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
Page | 31
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
SOURCE CODE:
import java.util.Scanner;
public class StringManipulation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input for the first string
System.out.print("Enter the first string: ");
String firstString = scanner.nextLine();
char[] firstCharArray = firstString.toCharArray(); // Convert to character array
// a) Get the length of the string
int length = firstCharArray.length;
System.out.println("Length of the first string: " + length);
// b) Finding a character at a particular position
System.out.print("Enter a position to find the character (0 to " + (length - 1) + "): ");
int position = scanner.nextInt();
if (position >= 0 && position < length) {
char characterAtPosition = firstCharArray[position];
System.out.println("Character at position " + position + ": " + characterAtPosition);
} else {
System.out.println("Invalid position!");
}
// Input for the second string
scanner.nextLine(); // Clear the buffer
System.out.print("Enter the second string: ");
String secondString = scanner.nextLine();
// c) Concatenating two strings
String concatenatedString = firstString + secondString;
System.out.println("Concatenated string: " + concatenatedString);
}
}
Page | 32
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
CODE EXPLANATION:
1. import java.util.Scanner;
o This imports the Scanner class, which is used to read input from the user.
2. public class StringManipulation {
o Declares a class named StringManipulation, which contains the program logic.
3. public static void main(String[] args) {
o Defines the main method, which is the entry point of the program.
4. Scanner scanner = new Scanner(System.in);
o Creates a Scanner object to read input from the console.
5. System.out.print("Enter the first string: ");
o Prompts the user to enter the first string.
6. String firstString = scanner.nextLine();
o Reads the first string input from the user, including spaces.
7. char[] firstCharArray = firstString.toCharArray();
o Converts the first string into a character array for easier manipulation.
8. int length = firstCharArray.length;
o Calculates the length of the first string using the length property of the character
array.
9. System.out.println("Length of the first string: " + length);
o Prints the length of the first string.
10. System.out.print("Enter a position to find the character (0 to " + (length - 1) + "): ");
o Prompts the user to enter a position to retrieve a character from the first string.
11. int position = scanner.nextInt();
o Reads the position input as an integer.
12. if (position >= 0 && position < length) {
o Checks if the entered position is within the valid range (0 to length-1).
13. char characterAtPosition = firstCharArray[position];
o Retrieves the character at the specified position from the character array.
14. System.out.println("Character at position " + position + ": " + characterAtPosition);
o Prints the character found at the specified position.
15. } else {
Page | 33
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 34
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT - 7
AIM:
To develop a Java program that demonstrates fundamental string operations, including String
Concatenation, Substring Search, and Substring Extraction.
ALGORITHM:
Page | 35
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
Page | 36
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
SOURCE CODE:
import java.util.Scanner;
public class SimpleStringOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Concatenation
System.out.print("Enter the first string: ");
String str1 = scanner.nextLine();
System.out.print("Enter the second string: ");
String str2 = scanner.nextLine();
String concatenated = str1 + str2;
System.out.println("Concatenated String: " + concatenated);
// Search for a substring
System.out.print("Enter a substring to search: ");
String substring = scanner.nextLine();
if (concatenated.contains(substring)) {
System.out.println("Substring found!");
} else {
System.out.println("Substring not found.");
}
// Extract a substring
System.out.print("Enter start index: ");
int start = scanner.nextInt();
System.out.print("Enter end index: ");
int end = scanner.nextInt();
if (start >= 0 && end <= concatenated.length()) {
String extracted = concatenated.substring(start, end);
System.out.println("Extracted Substring: " + extracted);
} else {
System.out.println("Invalid indices.");
}
Page | 37
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
}
}
CODE EXPLANATION:
1. import java.util.Scanner;
o Imports the Scanner class, which allows reading user input from the console.
2. public class SimpleStringOperations {
o Declares the class SimpleStringOperations, where the program logic will be
implemented.
3. public static void main(String[] args) {
o Defines the main method, which is the entry point of the program.
4. Scanner scanner = new Scanner(System.in);
o Creates a Scanner object named scanner to read input from the user.
5. System.out.print("Enter the first string: ");
o Prompts the user to enter the first string.
6. String str1 = scanner.nextLine();
o Reads the first string entered by the user and stores it in the variable str1.
7. System.out.print("Enter the second string: ");
o Prompts the user to enter the second string.
8. String str2 = scanner.nextLine();
o Reads the second string entered by the user and stores it in the variable str2.
9. String concatenated = str1 + str2;
o Concatenates str1 and str2 using the + operator and stores the result in the variable
concatenated.
10. System.out.println("Concatenated String: " + concatenated);
o Prints the concatenated string to the console.
11. System.out.print("Enter a substring to search: ");
o Prompts the user to enter a substring that they want to search for in the concatenated
string.
12. String substring = scanner.nextLine();
o Reads the substring entered by the user and stores it in the variable substring.
Page | 38
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
13. if (concatenated.contains(substring)) {
o Checks if the concatenated string contains the entered substring using the contains
method.
14. System.out.println("Substring found!");
o If the substring is found, it prints "Substring found!".
15. } else {
o If the substring is not found, it executes the code in this block.
16. System.out.println("Substring not found.");
o Prints "Substring not found." if the substring is not found in the concatenated string.
17. System.out.print("Enter start index: ");
o Prompts the user to enter the start index for the substring extraction.
18. int start = scanner.nextInt();
o Reads the start index entered by the user and stores it in the variable start.
19. System.out.print("Enter end index: ");
o Prompts the user to enter the end index for the substring extraction.
20. int end = scanner.nextInt();
o Reads the end index entered by the user and stores it in the variable end.
21. if (start >= 0 && end <= concatenated.length()) {
o Checks if the entered start and end indices are valid. Specifically, it ensures that the
start index is greater than or equal to 0 and the end index is less than or equal to the
length of the concatenated string.
22. String extracted = concatenated.substring(start, end);
o If the indices are valid, it extracts the substring from the concatenated string using
the substring method, from start to end index, and stores it in the extracted variable.
23. System.out.println("Extracted Substring: " + extracted);
o Prints the extracted substring to the console.
24. } else {
o If the indices are invalid, this block is executed.
25. System.out.println("Invalid indices.");
o Prints an error message indicating the indices provided are invalid.
26. }
Page | 39
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 40
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT - 8
AIM:
To create a Java program that utilizes the StringBuffer class to perform string operations:
determine string length, reverse the string, and delete a specified substring.
ALGORITHM:
Page | 41
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
Page | 42
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
SOURCE CODE:
import java.util.Scanner;
public class SimpleStringBuffer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input string
System.out.print("Enter a string: ");
StringBuffer sb = new StringBuffer(scanner.nextLine());
// Length of the string
System.out.println("Length: " + sb.length());
// Reverse the string
System.out.println("Reversed: " + sb.reverse());
// Delete a substring
System.out.print("Start index to delete: ");
int start = scanner.nextInt();
System.out.print("End index to delete: ");
int end = scanner.nextInt();
if (start >= 0 && end <= sb.length() && start < end) {
sb.delete(start, end);
System.out.println("After deletion: " + sb);
} else {
System.out.println("Invalid indices.");
}
}
}
CODE EXPLANATION:
1. import java.util.Scanner;
o Imports the Scanner class to read user input from the console.
2. public class SimpleStringBuffer {
Page | 43
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
Page | 44
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
o If the indices are valid, it deletes the substring from the start index to the end
index using the delete() method of StringBuffer.
15. System.out.println("After deletion: " + sb);
o Prints the modified string after the deletion.
16. } else {
o If the indices are invalid, this block is executed.
17. System.out.println("Invalid indices.");
o Prints an error message indicating that the indices provided are invalid.
18. }
o Closes the if-else block.
19. }
o Closes the main method.
20. }
o Closes the class definition.
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 45
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT - 9
AIM:
To implement a multi-threaded Java application that generates random integers and computes their
squares if even or cubes if odd, using three separate threads.
ALGORITHM:
Page | 46
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
SOURCE CODE:
import java.util.Random;
class RandomNumberGeneratorEx extends Thread {
private final NumberProcessor processor;
public RandomNumberGeneratorEx(NumberProcessor processor) {
this.processor = processor;
}
Page | 47
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
@Override
public void run() {
Random random = new Random();
while (true) {
int number = random.nextInt(100);
System.out.println("Generated: " + number);
processor.processNumber(number);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}
}
class NumberProcessor {
private int number;
public synchronized void processNumber(int number) {
this.number = number;
notifyAll();
}
public void square() {
while (true) {
synchronized (this) {
try {
wait();
if (number % 2 == 0) {
System.out.println("Square: " + (number * number));
}
} catch (InterruptedException e) {
break;
Page | 48
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
}
}
}
}
public void cube() {
while (true) {
synchronized (this) {
try {
wait();
if (number % 2 != 0) {
System.out.println("Cube: " + (number * number * number));
}
} catch (InterruptedException e) {
break;
}
}
}
}
}
Page | 49
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
CODE EXPLANATION:
Page | 50
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
o If the thread is interrupted, it will break out of the loop and stop execution.
13. }
o Ends the run() method.
NumberProcessor Class:
Square Method:
Page | 51
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
24. if (number % 2 == 0) {
o Check if the current number is even.
25. System.out.println("Square: " + (number * number));
o If the number is even, it calculates the square and prints it.
26. } catch (InterruptedException e) { break; }
o If the thread is interrupted, it breaks out of the loop and stops execution.
27. }
o Ends the synchronized block.
28. }
o Ends the square() method.
Cube Method:
Page | 52
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
Page | 53
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 54
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT - 10
AIM:
To implement a Java program that uses multi-threading to print numbers from 1 to 10 and from 90
to 100 asynchronously using the same method.
ALGORITHM:
Step 1: Start.
Step 2: Define the NumberPrinter Class.
Step 3: Declare attributes int start for the starting number and int end for the ending number.
Step 4: Create a constructor to initialize start and end with given values.
Step 5: In the run() method, loop from start to end (inclusive) and print the current number. Sleep
for 500 milliseconds and handle any InterruptedException by restoring the thread's interrupted
status.
Step 6: Define the AsyncNumberPrinting Class. In the main() method, create a Thread object t1
for printing numbers from 1 to 10 using NumberPrinter.
Step 7: Create another Thread object t2 for printing numbers from 90 to 100 using NumberPrinter.
Start both threads using t1.start() and t2.start().
Step 8: End the Process.
Page | 55
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
SOURCE CODE:
class NumberPrinter extends Thread {
private final int start;
private final int end;
public NumberPrinter(int start, int end) {
this.start = start;
this.end = end;
}
@Override
Page | 56
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
CODE EXPLANATION:
NumberPrinter Class:
Page | 57
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
9. System.out.println(i);
o Prints the current value of i to the console, which is the current number in the loop.
10. try { Thread.sleep(500); }
o Pauses the execution of the current thread for 500 milliseconds (half a second) to
allow for better visibility of the printed numbers.
11. catch (InterruptedException e) {
o Catches any InterruptedException that may occur during the Thread.sleep()
operation. This exception occurs if the thread is interrupted while sleeping.
12. Thread.currentThread().interrupt();
o Restores the interrupted status of the current thread after the exception is caught.
This ensures that the interruption is not lost, and can be handled appropriately if
needed.
13. }
Page | 58
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
22. t2.start();
o Starts the thread t2, which also invokes the run() method of NumberPrinter. This
will begin printing the numbers from 90 to 100.
23. }
o Ends the main() method.
24. }
Page | 59
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 60
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT – 11
AIM:
ALGORITHM:
Step 1: Start.
Step 2: Initialize Scanner for user input.
Step 3: Arithmetic Exception: Prompt for a number to divide 10 by. Try to calculate and print 10
divided by the number. If ArithmeticException occurs, print "Error: Cannot divide by zero!"
Step 4: Number Format Exception: Prompt for a number. Try to read it as a string and convert it
to an integer. If NumberFormatException occurs, print "Error: Invalid number format!"
Step 5: ArrayIndexOutOfBoundsException: Initialize an array {1, 2, 3}. Prompt for an index. Try
to print the array value at that index. If ArrayIndexOutOfBoundsException occurs, print "Error:
Index out of bounds!"
Step 6: NegativeArraySizeException: Prompt for an array size. Try to create an array of that size
and print a success message. If NegativeArraySizeException occurs, print "Error: Size cannot be
negative!"
Step 7: End the Process.
Page | 61
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
Page | 62
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
SOURCE CODE:
import java.util.Scanner;
public class SimpleExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// a) Arithmetic Exception
try {
System.out.print("Divide 10 by: ");
int num = scanner.nextInt();
System.out.println("Result: " + (10 / num));
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero!");
}
// c) ArrayIndexOutOfBoundsException
try {
int[] array = {1, 2, 3};
System.out.print("Access index (0-2): ");
int index = scanner.nextInt();
System.out.println("Array value: " + array[index]);
} catch (ArrayIndexOutOfBoundsException e) {
Page | 63
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
// d) NegativeArraySizeException
try {
System.out.print("Enter array size: ");
int size = scanner.nextInt();
int[] array = new int[size]; // May throw NegativeArraySizeException
System.out.println("Array created with size: " + size);
} catch (NegativeArraySizeException e) {
System.out.println("Error: Size cannot be negative!");
}
}
}
CODE EXPLANATION:
import java.util.Scanner;
• Imports the Scanner class from the java.util package, allowing user input via the console.
• Defines the SimpleExceptionDemo class. This is the main class that contains the
program's logic.
• Defines the main method. The entry point of the program where the execution begins.
• Creates a Scanner object named scanner to read input from the console (standard input
stream, System.in).
// a) Arithmetic Exception
• This is a comment that marks the start of the block of code handling the
ArithmeticException.
Page | 64
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
try {
• Begins the try block. Any code that may throw an exception is placed inside this block.
• Reads an integer input from the user and stores it in the variable num.
} catch (ArithmeticException e) {
• Catches the ArithmeticException if it occurs (e.g., division by zero). This is part of the
exception handling mechanism.
• This is a comment marking the start of the block of code handling the
NumberFormatException.
try {
• Begins another try block. Any code inside this block may potentially throw an exception,
in this case, related to number parsing.
• Reads the user input as a string and attempts to parse it into an integer using
Integer.parseInt(). If the user enters a non-integer value, a NumberFormatException will
be thrown.
Page | 65
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
} catch (NumberFormatException e) {
• This is a comment marking the start of the block of code handling the
ArrayIndexOutOfBoundsException.
try {
• Begins another try block. This block contains code that may throw an
ArrayIndexOutOfBoundsException.
• Reads the user's input as an integer, which represents the index to access in the array.
• Tries to access the value at the specified index in the array and print it. If the index is out
of bounds (less than 0 or greater than 2), it will throw an
ArrayIndexOutOfBoundsException.
} catch (ArrayIndexOutOfBoundsException e) {
Page | 66
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
// d) NegativeArraySizeException
• This is a comment marking the start of the block of code handling the
NegativeArraySizeException.
try {
• Begins another try block. This block contains code that may throw a
NegativeArraySizeException.
• Reads the user's input as an integer, which represents the size of the array to be created.
• Attempts to create an array of integers with the size specified by the user. If the user
enters a negative number, a NegativeArraySizeException will be thrown.
• If the array is successfully created, this line prints the size of the array.
} catch (NegativeArraySizeException e) {
• Catches the NegativeArraySizeException if the user enters a negative size for the array.
Page | 67
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 68
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT – 12
AIM:
To create a Java program that retrieves and displays file information, including existence,
readability, writability, type, and size, based on user-provided filename.
ALGORITHM:
Step 1: Start the Process.
Step 2: Initialize the Scanner to read user input.
Step 3: Prompt for filename and read input.
Step 4: Create a File object using the filename.
Step 5: Check if the file exists. If it exists, print "File exists: Yes." Check if it is readable and
writable, then print the results. Determine if it’s a directory or a file, and print the type. Finally,
print the size in bytes.
Step 6: If the file does not exist, print "File exists: No."
Step 7: End the Process.
Page | 69
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
Page | 70
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
SOURCE CODE:
import java.io.File;
import java.util.Scanner;
public class SimpleFileInfo {
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("Readable: " + file.canRead());
System.out.println("Writable: " + file.canWrite());
System.out.println("Type: " + (file.isDirectory() ? "Directory" : "File"));
System.out.println("Size: " + file.length() + " bytes");
} else {
System.out.println("File exists: No");
}
}
}
CODE EXPLANATION:
import java.io.File;
● This line imports the File class from the java.io package, which is used to
create and manage file and directory pathnames in Java.
import java.util.Scanner;
● This line imports the Scannerclass from the java.util
package, which is used to read input from the user.
public class SimpleFileInfo {
● This line declares the SimpleFileInfo class, which is themain class of the
program.
Page | 71
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
Page | 72
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
else {
● This line marks the beginning of the elseblock, which isexecuted if the
file does not exist.
System.out.println("File exists: No");
● If the file does not exist, this line prints "File exists: No" to theconsole.
}
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 73
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT - 13
AIM:
To create a simple Java GUI program that allows users to input text and display it with basic
formatting options.
ALGORITHM:
Step 1: Start the Process.
Step 2: Initialize Frame: Create a JFrame titled "Text Formatter", set size to 300x250 pixels, set
close operation to exit, and set layout to FlowLayout.
Step 3: Create Components: Create a JTextField for input (15 columns), a JButton labeled
"Format Text", and a non-editable JTextArea for displaying formatted text (5 rows, 20 columns).
Step 4: Add Components to Frame: Add the JTextField, JButton, and JTextArea (inside a
JScrollPane) to the frame.
Step 5: Add Action Listener to Button: On button click, retrieve text from JTextField, display it
in JTextArea, and set font to Arial, plain style, size 16.
Step 6: Make Frame Visible: Set the frame to visible.
Step 7: End the Process.
Page | 74
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
Page | 75
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
SOURCE CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleTextFormatter extends JFrame {
private JTextField textField;
private JTextArea textArea;
public SimpleTextFormatter() {
// Frame setup
setTitle("Text Formatter");
setSize(300, 250);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Text input
textField = new JTextField(15);
add(textField);
// Button to apply formatting
JButton formatButton = new JButton("Format Text");
add(formatButton);
// Display area for formatted text
textArea = new JTextArea(5, 20);
textArea.setEditable(false);
add(new JScrollPane(textArea));
// Button action
formatButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
formatText();
}
});
Page | 76
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
setVisible(true);
}
private void formatText() {
String text = textField.getText();
textArea.setText(text); // Display the text
textArea.setFont(new Font("Arial", Font.PLAIN, 16)); // Set a default font
}
public static void main(String[] args) {
new SimpleTextFormatter();
}
}
CODE EXPLANATION:
import javax.swing.*;
● Imports all classes from the javax.swing package. This package is used to
create graphical user interfaces (GUIs) inJava, including components like
JFrame, JTextField, JTextArea, and JButton.
import java.awt.*;
● Imports all classes from the java.awt package. This packageprovides graphical
components and utilities for handling graphical user interfaces, including
FlowLayoutand Font.
import java.awt.event.ActionEvent;
● Imports the ActionEvent class from the java.awt.event package, which is used
to handle action events like buttonclicks.
import java.awt.event.ActionListener;
Page | 77
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
● Declares a JTextField object called textField. This will beused to allow the user
to input text.
private JTextArea textArea;
● Sets the size of the JFrame window to be 300 pixels wide and 250 pixels tall.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
● Specifies that the application will close when the user clicksthe "X" button
on the window.
setLayout(new FlowLayout());
● Sets the layout manager for the JFrame to FlowLayout. This layout manager
arranges components in a left-to-right flow, one after another.
textField = new JTextField(15);
Page | 78
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
add(textField);
● Adds the textFieldcomponent to the JFrame window so that the user can see and
interact with it.
JButton formatButton = new JButton("Format Text");
● Creates a new JButton with the label "Format Text". This button will trigger
the text formatting action when clicked.
add(formatButton);
● Adds the formatButtonto the JFrame window so the user can click it to
format the text.
textArea = new JTextArea(5, 20);
● Initializes the textArea object as a new JTextArea with 5 rows and 20 columns.
This area will be used to display theformatted text.
textArea.setEditable(false);
● Sets the textArea to be non-editable by the user. This ensures that the user
can only see the formatted text, notmodify it directly.
add(new JScrollPane(textArea));
● Wraps the textAreain a JScrollPaneto allow scrolling whenthe content exceeds the
visible area. The JScrollPane is thenadded to the JFrame.
formatButton.addActionListener(new ActionListener() {
Page | 79
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
formatText();
● Calls the formatText() method, which will format the text entered in the
textFieldand display it in the textArea.
});
● Closes the addActionListener method.
setVisible(true);
● Makes the JFrame visible on the screen. Without this, the window would
not be displayed.
private void formatText() {
● Retrieves the text entered by the user in the textFieldandstores it in the text
variable.
textArea.setText(text);
● Sets the text in the textAreato the value of textretrievedfrom the textField.
textArea.setFont(new Font("Arial", Font.PLAIN, 16));
● Sets the font of the text in the textAreato Arial with a plainstyle and a size of
16.
public static void main(String[] args) {
● Defines the mainmethod, which is the entry point for runningthe program.
new SimpleTextFormatter();
Page | 80
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
OUTPUT
RESULT:
Thus, the program had been successfully executed.
Page | 81
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT – 14
AIM:
To create a simple Java GUI program that handles mouse events and displays the corresponding
event name in the center of the window.
ALGORITHM:
Step 1: Start the Process.
Step 2: Initialize Frame: Create a JFrame titled "Mouse Event Demo", set size to 400x300 pixels,
set close operation to exit, and set layout to BorderLayout.
Step 3: Create Label: Create a JLabel for displaying mouse event names, centered in the window,
and set font to Arial, size 24.
Step 4: Add Label to Frame: Add the JLabel to the center of the frame.
Step 5: Add Mouse Listener: Use MouseAdapter to handle events:
▪ On mouse click, set label text to "Mouse Clicked".
▪ On mouse enter set label text to "Mouse Entered".
▪ On mouse exit, set label text to "Mouse Exited".
Step 6: Make Frame Visible: Set the frame to visible.
Step 7: End the Process.
Page | 82
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
SOURCE CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
Page | 83
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
setVisible(true);
}
public static void main(String[] args) {
new SimpleMouseEventDemo();
}
}
CODE EXPLANATION:
import javax.swing.*;
● Imports all classes from the javax.swing package, which provides
components like JFrame, JLabel, and other GUI elements used in the
program.
import java.awt.*;
● Imports all classes from the java.awt package, which includes components and
utilities for handling graphical userinterfaces, such as BorderLayoutand Font.
Page | 84
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
import java.awt.event.MouseAdapter;
● Declares a JLabel object called label, which will be used todisplay text that
responds to mouse events.
public SimpleMouseEventDemo() {
● Sets the title of the JFrame window to "Mouse Event Demo". This title
will appear at the top of the window.
setSize(400, 300);
● Sets the size of the window to be 400 pixels wide and 300pixels tall.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
● Specifies that the program should terminate when the userclicks the
"close" button (the "X" in the window's corner).
Page | 85
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
setLayout(new BorderLayout());
● Sets the layout manager for the JFrame to BorderLayout. This layout
manager divides the window into five regions (North, South, East, West,
and Center). In this case, the labelwill be placed in the center.
label = new JLabel("", SwingConstants.CENTER);
● Initializes the labelas a new JLabel. The text of the label isinitially set to an
empty string (""), and the SwingConstants.CENTER argument ensures that the
label’stext is centered within the label.
label.setFont(new Font("Arial", Font.PLAIN, 24));
● Sets the font of the label's text to Arial, with a plain style and asize of 24
points.
add(label, BorderLayout.CENTER);
● Adds the labelto the center of the JFrame using the BorderLayout.CENTER
position. This places the label in thecentral part of the window.
addMouseListener(new MouseAdapter() {
● Defines the mouseClicked method, which is called when theuser clicks the
mouse inside the JFrame.
label.setText("Mouse Clicked");
● Sets the text of the label to "Mouse Clicked" when the mouse isclicked.
public void mouseEntered(MouseEvent e) {
● Defines the mouseEntered method, which is called when themouse pointer
enters the JFrame window.
label.setText("Mouse Entered");
● Sets the text of the label to "Mouse Entered" when the mousepointer enters
Page | 86
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
the window.
public void mouseExited(MouseEvent e) {
● Defines the mouseExited method, which is called when themouse pointer
exits the JFrame window.
label.setText("Mouse Exited");
● Sets the text of the label to "Mouse Exited" when the mousepointer exits
the window.
});
● Closes the MouseAdapter declaration and the addMouseListener method. The
program is now listening formouse events.
setVisible(true);
● Makes the JFrame window visible on the screen. Without this, the window
would remain hidden.
public static void main(String[] args) {
● Defines the mainmethod, which is the entry point for runningthe program.
new SimpleMouseEventDemo();
Page | 87
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
OUTPUT
RESULT:
Thus, the program had been successfully executed.
Page | 88
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT – 15
AIM:
To create a simple Java calculator using a GUI that performs basic arithmetic operations and
handles exceptions like division by zero.
ALGORITHM:
Step 1: Start the Process.
Step 2: Create GUI: Set up JFrame, JTextField, and buttons.
Step 3: Set layout: Use BorderLayout for the frame and GridLayout for buttons.
Step 4: Create buttons: Define button labels for digits and operations in an array.
Step 5: Add buttons: Loop through the array to create and add buttons.
Step 6: Handle clicks: Attach action listeners to all buttons.
Step 7: Input number: Append digits to the display when pressed.
Step 8: Input operator: Store the first number and operator when an operator is pressed.
Step 9: Calculate: Operate on the second number when = is pressed.
Step 10: Show result: Display the result, and handle division by zero error.
Step 11: Clear: Reset everything when C is pressed.
Step 12: End the Process.
Page | 89
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
Page | 90
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
SOURCE CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleCalculator extends JFrame implements ActionListener {
// Components
JTextField display;
double num1 = 0, num2 = 0, result = 0;
char operator;
// Constructor
public SimpleCalculator() {
// Frame settings
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Create display field
display = new JTextField();
display.setEditable(false);
add(display, BorderLayout.NORTH);
// Create panel for buttons
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
// Button labels
String[] buttons = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"C", "0", "=", "/"
};
Page | 91
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
Page | 92
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
} else {
display.setText("Error");
return;
}
break;
}
display.setText(String.valueOf(result));
} else {
// Store the first number and the operator
num1 = Double.parseDouble(display.getText());
operator = command.charAt(0);
display.setText("");
}
}
// Main method to run the calculator
public static void main(String[] args) {
new SimpleCalculator();
}
}
CODE EXPLANATION:
import javax.swing.*;
Imports the necessary classes from the javax.swing package,which is used for building
graphical user interface (GUI) components such as JFrame, JButton, and JTextField.
import java.awt.*;
Imports the java.awt package, which provides classes for creating and managing user
interfaces, layout managers like BorderLayout and GridLayout, and other UI components
likeFontand Color.
import java.awt.event.ActionEvent;
Imports the ActionEvent class, which represents an action event, such as when a
button is clicked
import java.awt.event.ActionListener;
Imports the ActionListener interface, which is used to handle action events. The
Page | 93
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
Page | 94
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
Page | 95
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
clicked, the display will show "7",and if "1" is clicked next, the display will show
"71".
else if (command.equals("C")) {
Check if the "C" button was clicked. If it is clicked, it clearsthe display and resets
the numbers and result.
display.setText("");
Clears the display field.
num1 = num2 = result = 0;
Resets all the variables (num1, num2, and result) to 0.
else if (command.equals("=")) {
Checks if the "=" button was clicked, which triggers thecalculation.
num2 = Double.parseDouble(display.getText());
Converts the text in the display field to a double value andstores it in num2.
switch (operator) {
Uses a switchstatement to perform the calculation based onthe selected operator.
case '+': result = num1 + num2; break;
If the operator is '+', it adds num1and num2and stores theresult.
case '-': result = num1 - num2; break;
If the operator is '-', it subtracts num2from num1and storesthe result.
case '*': result = num1 * num2; break;
If the operator is '*', it multiplies num1and num2and stores theresult.
case '/':
If the operator is '/', it performs division. If num2is not 0, itdivides num1 by num2
and stores the result. If num2 is 0, itdisplays an "Error" message in the display field.
display.setText(String.valueOf(result));
Converts the resultto a string and displays it in the display field.
else {
If the clicked button is an operator (like +, -, *, or /), the current number in the display is
stored as num1, and theoperator is saved.
num1 = Double.parseDouble(display.getText());
Converts the current value in the display to a double andstores it in num1.
operator = command.charAt(0);
Sets the operatorvariable to the first character of thecommand (which is the
operator symbol).
Page | 96
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
display.setText("");
Clears
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 97
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
EXPERIMENT – 16
AIM:
To create a simple Java GUI application that simulates a traffic light using radio buttons to display
corresponding messages and colors for "Stop," "Ready," and "Go."
ALGORITHM:
Step 1: Start.
Step 2: Initialize Frame: Create a JFrame titled "Traffic Light Simulator", set size to 300x200
pixels, set close operation to exit, and set layout to FlowLayout.
Step 3: Create Message Label: Create a JLabel for traffic light messages, set font to Arial, bold,
size 24, and add it to the frame (initially empty).
Step 4: Create Radio Buttons: Create JRadioButton objects for "Red", "Yellow", and "Green".
Step 5: Group Radio Buttons: Use a ButtonGroup to allow only one radio button to be selected at
a time.
Step 6: Add Buttons to Frame: Add the radio buttons to the frame.
Step 7: Add Action Listeners: For each radio button:
▪ Red: Call updateMessage("Stop", Color.RED).
▪ Yellow: Call updateMessage("Ready", Color.YELLOW).
▪ Green: Call updateMessage("Go", Color.GREEN).
Step 8: Define updateMessage Method: Set the label text and color based on input parameters.
Step 9: Make Frame Visible: Set the frame to visible.
Step 10: End the Process.
Page | 98
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
FLOW CHART:
SOURCE CODE:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleTrafficLightSimulator extends JFrame {
private JLabel messageLabel;
public SimpleTrafficLightSimulator() {
setTitle("Traffic Light Simulator");
Page | 99
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
messageLabel = new JLabel(""); // Initial empty message
messageLabel.setFont(new Font("Arial", Font.BOLD, 24));
add(messageLabel);
// Create radio buttons for traffic lights
JRadioButton redButton = new JRadioButton("Red");
JRadioButton yellowButton = new JRadioButton("Yellow");
JRadioButton greenButton = new JRadioButton("Green");
// Group buttons so only one can be selected
ButtonGroup group = new ButtonGroup();
group.add(redButton);
group.add(yellowButton);
group.add(greenButton);
add(redButton);
add(yellowButton);
add(greenButton);
// Action listener for buttons
redButton.addActionListener(e -> updateMessage("Stop", Color.RED));
yellowButton.addActionListener(e -> updateMessage("Ready", Color.YELLOW));
greenButton.addActionListener(e -> updateMessage("Go", Color.GREEN));
setVisible(true);
}
private void updateMessage(String message, Color color) {
messageLabel.setText(message);
messageLabel.setForeground(color);
}
public static void main(String[] args) {
new SimpleTrafficLightSimulator();
}
Page | 100
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
CODE EXPLANATION:
Importing Libraries:
The code begins by importing necessary Java libraries for creatinggraphical user
interfaces (GUI) using Swing, and for handling events:
● javax.swing.*for GUI components like buttons and labels.
● java.awt.* for layouts and colors.
● java.awt.event.ActionEvent and java.awt.event.ActionListener to handle user
actions(like button clicks).
Class Definition:
The SimpleTrafficLightSimulator class extends JFrame, meaning it represents a window
where the GUI will be displayed.
● setTitle("Traffic Light Simulator"): This sets the titleof the window to "Traffic
Light Simulator".
● setSize(300, 200): Specifies the window size (300 pixelswide and 200 pixels
tall).
● setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE): Thisensures that the
program will close when the window is closed.
● setLayout(new FlowLayout()): The layout manager is set toFlowLayout, meaning
components will be added sequentially from left to right.
Message Label:
● messageLabel = new JLabel("");: Creates a label that willdisplay the traffic light
message (initially empty).
● messageLabel.setFont(new Font("Arial", Font.BOLD,24)): Sets the font style
and size for the label.
● add(messageLabel): Adds the label to the window.
Radio Buttons for Traffic Lights:
● Three JRadioButton components (redButton, yellowButton,greenButton) are
created for the red, yellow, and green lights.
Page | 101
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
Main Method:
● public static void main(String[] args): This is theentry point for the program.
Page | 102
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS
JAVA PROGRAMMING – LAB MANUAL
OUTPUT:
RESULT:
Thus, the program had been successfully executed.
Page | 103
2024 BATCH ONWARDS – AUTONOMOUS
CS / BCA / IT / CT / AI&DS