java lab
java lab
INDO-AMERICAN COLLEGE
CHEYYAR-604 407
JAVAJAVA
PROGRAMMING
PROGRAM LAB LAB
2024-2025
Reg. No:…………………………………………
Name:……………………………………………
Class:……………………………………………..
THIRUVALLUVAR UNIVERSITY
INDO-AMERICAN COLLEGE
CHEYYAR-604 407
Examiners:
Place: 1.
DATE: 2.
S DATE TITLE PG.
NO SIGN
NO.
12.03.25
CALCULATOR USE A GRID LAYOUT 55
14
13.03.25
SIMULATES A TRAFFIC LIGHT 60
15
EX.NO:1
AIM
The aim of this program is to print all the prime numbers from 2 up to the user provided input
ALGORITHM
Step1:start
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.
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:
3
RESULT:
AIM:
The aim of this program is to perform matrix multiplication of two user-input matrices
ALGORITHM:
Step 1:start
Step2:
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:
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).
Step5: stop
5
PROGRAM
import java.util.Scanner;
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
8
RESULT:
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
1.The program uses a Scanner to read input from the user line by line until the user types "END".
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;
11
OUTPUT
Analysis Result:
Number of characters: 41
Number of lines: 2
Number of words: 6
12
RESULT:
13
EX.NO:4 GENERATE RANDOM NUMBERS BETWEEN TWO GIVEN LIMITS USING RANDOM CLASS
AIM:
To writ a java program using random numbers
ALGORITHM:
STEP 1:start
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]
o After determining the range, print the random number and its corresponding range.
STEP 5:Stop
14
PROGRAM
import java.util.Random;
15
OUTPUT
16
RESULT:
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
20
RESULT:
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
Concatenate str1 and str2 using the concat() method to form cString.
Ask the user to provide start and end indices ( sInd, eInd).
Extract the substring from str1 using substring(sInd, eInd).
STEP 7:Stop
22
PROGRAM
import java.io.DataInputStream;
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
23
OUTPUT
24
RESULT
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
Use the length() method of String Buffer to calculate the length of the string.
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;
scanner.close();
}
}
27
OUTPUT
28
RESULT
29
EX.NO: 8
DATE:24.02.25 MULTITHREAD
AIM:
To write a java program using multithread.
ALGORITHM:
STEP 1:start
If the generated number is even, the Even Processor thread processes it by calculating the square of
that number.
If the generated number is odd, the Odd Processor thread processes it by calculating the cube of that
number.
STEP 5:Threads:
STEP 6:Stop
30
PROGRAM:
import java.util.Random;
SquareThread(int randomNumbern) {
number = randomNumbern;
}
CubeThread(int randomNumber) {
number = randomNumber;
}
32
OUTPUT
Random Integer generated : 94
Square of 94 = 8836
Cube of 59 = 205379
Square of 24 = 576
Square of 50 = 2500
Square of 66 = 4356
Square of 80 = 6400
Cube of 7 = 343
Square of 24 = 576
Cube of 67 = 300763
Cube of 93 = 804357.
33
RESULT
AIM:
To write a java program using threading program
ALGORITHM:
STEP 1:start
STEP 2: Create a Number Printer object:
When the threads are started, they execute their respective tasks (printing numbers).
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) {
thread1.start();
thread2.start();
}
}
class NumberPrinter {
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
38
EX.NO: 10 EXCEPTION HANDLING
DATE: 05.03.25
AIM:
To write a java program using exception handling
ALGORITHM:
STEP 1:start
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.
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
RESULT
41
EX.NO: 11 FILE HANDLING
DATE: 06.03.25
AIM:
To write a java program using file handling
Algorithm:
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
44
RESULT
45
EX.NO: 12 WRITE FROM A PROGRAM TO ACCEPT A TEXT AND
AIM:
To write a java program using accept a text and changes
ALGORITHM:
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.
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.
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
AIM:
To write a java program using handles all mouse events
ALGORITHM:
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.
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").
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
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:
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.
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.
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.
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
AIM:
To write a java program using simulates a traffic light
ALGORITHM:
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.
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.
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.
Add the radio buttons panel (radioPanel) and the message panel (messagePanel) to the frame
using BorderLayout.
Make the frame visible.
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