Java Lab Class (5)
Java Lab Class (5)
AIM
To write a java program to get an integer from user and to print all prime numbers
upto that integer.
ALGORITHM
Step 1: Start the program.
Step 2: Declare an integer variable n, p to hold the user input.
Step 3: Using a Scanner object s, to read user input from the console.
Step 4: Read the integer input from the user and store it in variable n.
Step 5: Initialize a loop with variable i=2 and continue looping until i is less than n.
Step 6: Inside this loop, set p to 0.
Step 7: Initialize another loop with variable j=2 and continue looping until j is less than i.
Step 8: Check if i is divisible by j (i % j == 0) then set p to 1 indicating that i is not prime and
break the inner loop.
Step 9: If p is 0, then i is prime, print the value of i.
Step 10: Stop the program.
Program
import java.util.Scanner;
class PrimeNumbers
{
public static void main(String[] args)
{
int n;
int p;
Scanner s=new Scanner(System.in);
System.out.println("Enter a number: ");
n=s.nextInt();
System.out.println("The Prime Numbers upto"+ n +"are :");
for(int i=2;i<n;i++)
{
p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
System.out.println(i);
}
}
}
Class Diagram
OUTPUT
Enter a number:
50
The Prime Numbers upto50 are :
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
RESULT
Thus, the java program to get an integer from user and to print all prime
numbers upto that integer has been created and executed successfully.
Ex:2 MATRIX MULTIPLICATION
AIM
To write a java program to multiply two given matrices.
ALGORITHM
Step 1: Start the program.
Step 2: Declare an integer variable m, n ,p and q to store matrix dimensions and sum, c, d,
and k for loop counters.
Step 3: Read number of rows and columns for both the matrices from user.
Step 4: Using nested loops read the matrices.
Step 5: If n (columns of first matrix) is not equal to p (rows of the second matrix), then print
no matrix multiplication operation and terminate the program.
Step 6: Initialize nested loops to perform matrix operations.
Step 7: Compute multiplication and addition as sum += first[c][k] * second[k][d].
Step 8: Store sum in the result matrix as multiply[c][d] = sum.
Step 9: Print the product Matrices.
Step 10: Stop the program.
Program
import java.util.Scanner;
class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of first matrix");
m = in.nextInt();
n = in.nextInt();
multiply[c][d] = sum;
sum = 0;
}
}
System.out.print("\n");
}
}
}
}
Class Diagram
OUTPUT
Enter the number of rows and columns of first matrix
2
2
Enter elements of first matrix
2
4
6
8
Enter the number of rows and columns of second matrix
2
2
Enter elements of second matrix
1
3
5
7
Product of the matrices:
22 34
46 74
RESULT
Thus, the java program to multiply two given matrices has been created
and executed successfully.
Ex:3 DISPLAYS THE NUMBER OF CHARACTERS, LINES AND WORDS
IN A TEXT
AIM
To write a java program to displays the number of characters, lines and words in a
text.
ALGORITHM
Step 1: Start the program.
Step 2: Declare a string variable filePath to store the location of the file.
Step 3: Initialize three integer counters as characterCount, lineCount, and wordCount to zero.
Step 4: Create an object br for BufferedReader class to read the specified file.
Step 5: Use a while loop and br.readLine() function to read each line in the file.
Step 6: Using line.length() function add the length to characterCount.
Step 7: Remove leading and trailing whitespace from the current line using line.trim().
Step 8: Split the line into words and update wordCount.
Step 9: Print the results for characters, lines, and words.
Step 10: Stop the program.
Program
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Class Diagram
OUTPUT
Result
Thus, the java program to displays the number of characters, lines and
words in a text has been created and executed successfully.
Ex:4 GENERATE RANDOM NUMBERS BETWEEN TWO LIMITS
AIM
To write a java program to Generate random numbers between two given limits
using Random class.
ALGORITHM
Step 1: Start the program.
Step 2: Create a Scanner object to read input from the user.
Step 3: Create a Random object to generate random numbers.
Step 4: Read the lowerLimit and upperLimit integer input from the user and store it in the
variable.
Step 5: If lowerLimit is greater than or equal to upperLimit, then Display the message as
Invalid limits.
Step 6: Calculate a random number using the formula: randomNumber = random.nextInt
(upperLimit - lowerLimit) + lowerLimit.
Step 7: Compute range1 as: range1 = lowerLimit + (upperLimit - lowerLimit) / 3.
Step 8: Compute range2 as: range2 = lowerLimit + 2 * (upperLimit - lowerLimit) / 3.
Step 9: Print the random numbers and the range
Step 10: Stop the program.
Program
import java.util.Random;
import java.util.Scanner;
} else
{
System.out.println("The number is in the High range.");
}
scanner.close();
}
}
Class Diagram
OUTPUT
Result
Thus, the java program to Generate random numbers between two
given limits using Random class has been created and executed successfully.
Ex:5 STRING MANIPULATION
[LENGTH, CHARACTER POSITION AND CONCATENATION]
AIM
To write a java program to find string length, character position and to compute
concatenation operations.
ALGORITHM
Step 1: Start the program.
Step 2: Create a Scanner object to read input from the user.
Step 3: Read the input string and store it in str1 and str2.
Step 4: Convert str1and str2 to a character array charArray1 and charArray2.
Step 5: Calculate and print the length of charArray1.
Step 6: Read the integer input to find the position of the character.
Step 7: Print the character of the position1 in charArray1. If position1 is between 0 and the
length of charArray1 otherwise print error message.
Step 8: Concatenate str1 and str2 and store the result in concatenatedString.
Step 9: Display Concatenated String
Step 10: Stop the program.
Program
import java.util.Scanner;
scanner.close();
}
}
Class diagram
OUTPUT
Enter the first string: Java Programming
Enter the second string: Language
Result
Thus, the java program to find string length, character position and to
compute concatenation operations has been created and executed successfully.
Program
import java.util.Scanner;
public class StringOperations
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first string: ");
String firstString = scanner.nextLine();
scanner.close();
}
}
OUTPUT
Enter the first string: Hello java
Enter the second string: world
Concatenated string: Hello javaworld
Enter a substring to search: java
The substring 'java' is found in the first string.
Enter the starting index for substring extraction: 6
Enter the ending index for substring extraction: 10
Extracted substring: java
Result
Thus, the java program to perform string concatenation, search substring
and to extract substring using string class has been created and executed
successfully.
Program
import java.util.Scanner;
public class StringBufferOperations
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
if (startIndex != -1)
{
int endIndex = startIndex + substringToDelete.length();
stringBuffer.delete(startIndex, endIndex);
scanner.close();
}
}
OUTPUT
Enter a string: Hello world welcome to java programming
Length of the string: 39
Reversed string: gnimmargorp avaj ot emoclew dlrow olleH
Enter the substring to delete: world
Modified string: Hello welcome to java programming
Result
Thus, the java program to find the length of the given string, reverse the string
and to perform the delete operation using stringbuffer class has been created and
executed successfully.
Ex:8 MULTITHREADING
AIM
To write a java program to implement a multithread application and to print random
integer for every one second in the first thread, print square for even numbers in the second
thread and third thread print cube for odd numbers.
ALGORITHM
Step 1: Start the program.
Step 2: Define RandomNumberThread Class and Create an instance of Random.
Step 3: Generate a random integer (0 to 99) and store it in randomInteger..
Step 4: Check if randomInteger is even then Create an instance of SquareThread passing
randomInteger else Create an instance of CubeThread passing randomInteger.
Step 5: Put the thread to sleep for 1 second (1000 milliseconds).
Step 6: Define SquareThread Class and an instance variable number..
Step 7: Initialize number with the passed integer.Calculate and print the square of number.
Step 8: Define CubeThread Class and an instance variable number.
Step 9: Initialize number with the passed integer. Calculate and print the cube of number.
Step 10: Stop the program.
Program
import java.util.Random;
class RandomNumberThread extends Thread
{
public void run()
{
Random random = new Random();
for (int i = 0; i < 10; i++)
{
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " +
randomInteger);
if((randomInteger%2) == 0)
{
SquareThread sThread = new SquareThread(randomInteger);
sThread.start();
}
else {
CubeThread cThread = new CubeThread(randomInteger);
cThread.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
SquareThread(int randomNumbern) {
number = randomNumbern;
}
CubeThread(int randomNumber) {
number = randomNumber;
}
Result
Thus, the java program to implement a multithread application and to print
random integer for every one second in the first thread, print square for even numbers in the
second thread and third thread print cube for odd numbers has been created and
executed successfully.
Ex:9 THREADING USING ASYNCHRONOUS METHOD
AIM
To write a java program to implement asynchronous multithread application and to
print numbers from 1 to 10 in thread1 and 90 to 100 in thread2.
ALGORITHM
Step 1: Start the program.
Step 2: Define NumberPrinter Class and Implement the Runnable interface.
Step 3: Declare private instance variables as start and end.
Step 4: In Override run() method, using for loop print the value of i.
Step 5 Pause the thread for 100 milliseconds using Thread.sleep(100).
Step 6: If an InterruptedException occurs, Set the current thread's interrupt flag using
Thread.currentThread().interrupt().
Step 7: Create a Thread object thread1 and initialize it with NumberPrinter(1, 10).
Step 8: Create another Thread object thread2 and initialize it with NumberPrinter(90, 100).
Step 9: Start thread1 and thread2 and print the result.
Step 10: Stop the program.
Program
{
public static void main(String[] args)
{
Thread thread1 = new Thread(new NumberPrinter(1, 10));
Thread thread2 = new Thread(new NumberPrinter(90, 100));
thread1.start();
thread2.start();
try
{
thread1.join();
thread2.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
System.out.println("Both threads have completed their execution.");
}
}
OUTPUT
1
90
2
91
3
92
4
93
5
94
95
6
96
7
97
8
98
9
99
10
100
Both threads have completed their execution.
Result
Thus, the java program to implement asynchronous multithread application and to print
numbers from 1 to 10 in thread1 and 90 to 100 in thread2 has been created and executed
successfully.
AIM
To write a java program to implement exception handling.
ALGORITHM
Step 1: Start the program.
Step 2: Create an instance of Scanner to read input from the user.
Step 3: Read the user input as an integer and store it in a variable named divisor.
Step 4: Calculate the result of dividing 100 by divisor and print the result.
Step 5: If an exception occurs (e.g., division by zero), print an appropriate error message.
Step 6: Read the user input as a string and store it in numberString.
Step 7: If an exception occurs (e.g., input is not a valid integer), print an appropriate error
message.
Step 8: Define an integer array numbers and Read the index as an integer and store it in
index.
Step 9: If an exception occurs (e.g., index is out of bounds), print an appropriate error
message.
Step 10: Read the size as an integer and store it in size.
Step 11: If an exception occurs (e.g., size is negative), print an appropriate error message.
Step 12: Stop the program.
Program
import java.util.Scanner;
public class ExceptionDemo
{
System.out.println("Demonstrating ArithmeticException:");
try
{
System.out.print("Enter a number to divide 100: ");
int divisor = scanner.nextInt();
int result = 100 / divisor;
System.out.println("Result is: " + result);
}
catch (ArithmeticException e)
{
System.out.println("Error: Division by zero is not allowed.");
}
System.out.println("\nDemonstrating NumberFormatException:");
try
{
System.out.print("Enter a number: ");
String numberString = scanner.next();
int number = Integer.parseInt(numberString);
System.out.println("You entered the number: " + number);
}
catch (NumberFormatException e)
{
System.out.println("Error: Invalid number format.");
}
System.out.println("\nDemonstrating ArrayIndexOutOfBounds Exception:");
try {
int[] numbers = {1, 2, 3};
System.out.print("Enter an index to access the array (0-2): ");
int index = scanner.nextInt();
System.out.println("Element at index " + index + ": " + numbers[index]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error: Index is out of bounds.");
}
System.out.println("\nDemonstrating NegativeArraySizeException:");
try
{
System.out.print("Enter a size for the array (must be positive): ");
int size = scanner.nextInt();
int[] array = new int[size];
System.out.println("Array created of size: " + size);
}
catch (NegativeArraySizeException e)
{
System.out.println("Error: Array size cannot be negative.");
}
scanner.close();
}
}
OUTPUT
Demonstrating ArithmeticException:
Enter a number to divide 100: 0
ERROR!
Error: Division by zero is not allowed.
Demonstrating NumberFormatException:
Enter a number: abc
ERROR!
Error: Invalid number format.
Demonstrating ArrayIndexOutOfBoundsException:
Enter an index to access the array (0-2): 5
ERROR!
Error: Index is out of bounds.
Demonstrating NegativeArraySizeException:
Enter a size for the array (must be positive): -5
ERROR!
Error: Array size cannot be negative.
Result
Thus, the java program to implement exception handling has been created and
executed successfully.
Ex:11 FILE HANDLING
AIM
To write a java program to implement file handling and to read a file name, display
the file exists, the file is readable or writable, the type and the length of the file in bytes.
ALGORITHM
Step 1: Start the program.
Step 2: Create an instance of Scanner to read input from the user.
Step 3: Read the user input as a string and store it in a variable named fileName.
Step 4: Create a new File object using the fileName entered by the user.
Step 5: Use the exists() method of the File object to check if the file exists print YES else print NO .
Step 6: Use canRead() method to check if the file is readable and print the result.
Step 7: Use canWrite() method to check if the file is writable and print the result.
Step 8: Use isDirectory() method to determine if the File represents a directory and print the
File type.
Step 9: Use length() method to get the size of the file in bytes and print the result
Step 10: Stop the program.
Program
import java.io.File;
import java.util.Scanner;
public class FileInformation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the file name (with path if not in the same directory): ");
String fileName = scanner.nextLine();
OUTPUT
E:\>javac FileInformation.java
E:\>java FileInformation
Enter the file name (with path if not in the same directory): e:\sample.txt
File exists: Yes
File is readable: true
File is writable: true
File type: File
File length: 60 bytes
Result
Thus, the java program to implement file handling and to read a file name, display the file
exists, the file is readable or writable, the type and the length of the file in bytes has been
created and executed successfully.
AIM
To write a java program to accept a text and change its size and font including bold
italic options using frames and controls.
ALGORITHM
Step 1: Start the program.
Step 2: Create a JFrame object and set the title to "Text Styler"and Set the size of the frame.
Step 3: Set the layout of the frame to BorderLayout.
Step 4: Initialize a JTextArea for text input and Enable line wrapping and set word wrapping
to true.
Step 5: Place the text area inside a JScrollPane to allow scrolling.
Step 6: Create a JComboBox to allow users to select a font size from the options.
Step 7: Create CheckBoxes for Bold and Italic.
Step 8: Create a JPanel to hold the controls and Add a JLabel, fontSizeComboBox,
boldCheckBox, and italicCheckBox to the control panel.
Step 9: Create a JButton labeled "Update Text Style". Add an ActionListener to the button.
Step 10: Add the JScrollPane (which contains the textArea) to the center of the frame.
Step 11: Add the controlPanel to the south position of the frame.
Step 12: Stop the program.
Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextStyler extends JFrame {
private JTextArea textArea;
private JComboBox<String> fontSizeComboBox;
private JCheckBox boldCheckBox;
private JCheckBox italicCheckBox;
public TextStyler() {
// Set up the frame
setTitle("Text Styler");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Create components
textArea = new JTextArea();
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(textArea);
// Update button
JButton updateButton = new JButton("Update Text Style");
updateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateTextStyle();
}
});
controlPanel.add(updateButton);
if (boldCheckBox.isSelected()) {
fontStyle |= Font.BOLD;
}
if (italicCheckBox.isSelected()) {
fontStyle |= Font.ITALIC;
}
Result
Thus, the java program to accept a text and change its size and font including bold italic
options using frames and controls has been created and executed successfully.
Ex:13 MOUSE EVENT HANDLING
AIM
To write a java program to handle all mouse events and show the event name at the
center of the window when a mouse event is fired.
ALGORITHM
Step 1: Start the program.
Step 2: Initialize the JFrame and Create a new instance of MouseEventDemo..
Step 3: Specify the dimensions (width: 400px, height: 300px) for the window.
Step 4: Use a BorderLayout for the frame to organize components.
Step 5: Create and Instantiate the JLabel to display mouse event messages.
Step 6: Add the label to the center of the frame.
Step 7: Implement a mouse listener by creating an anonymous subclass of MouseAdapter.
Step 8: Add this mouse listener to the MouseEventDemo frame using
addMouseListener() and Updating the Event Label.
Step 9: Stop the program.
Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public MouseEventDemo() {
// Set up the frame
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
@Override
public void mousePressed(MouseEvent e) {
updateEventLabel("Mouse Pressed");
}
@Override
public void mouseReleased(MouseEvent e) {
updateEventLabel("Mouse Released");
}
@Override
public void mouseEntered(MouseEvent e) {
updateEventLabel("Mouse Entered");
}
@Override
public void mouseExited(MouseEvent e) {
updateEventLabel("Mouse Exited");
}
@Override
public void mouseDragged(MouseEvent e) {
updateEventLabel("Mouse Dragged");
}
@Override
public void mouseMoved(MouseEvent e) {
updateEventLabel("Mouse Moved");
}
});
}
OUTPUT
Result
Thus, the java program to handle all mouse events and show the event name at the center
of the window when a mouse event is fired has been created and executed successfully.
Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public SimpleCalculator() {
// Frame properties
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 4));
@Override
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
case "C":
// Clear display
display.setText("");
num1 = 0;
operator = "";
break;
case "=":
// Calculate result
try {
double num2 = Double.parseDouble(display.getText());
double result;
if (operator == null) {
break;
}
switch (operator) {
case "+":
result = num1 + num2;
display.setText(String.valueOf(result));
break;
case "-":
result = num1 - num2;
display.setText(String.valueOf(result));
break;
case "*":
result = num1 * num2;
display.setText(String.valueOf(result));
break;
case "/":
if (num2 == 0) {
display.setText("Error: Divide by zero");
} else {
result = num1 / num2;
display.setText(String.valueOf(result));
}
break;
case "%":
result = num1 % num2;
display.setText(String.valueOf(result));
break;
}
} catch (NumberFormatException ex) {
display.setText("Error: Invalid Input");
}
break;
default:
// Handle digits and operator buttons
if ("+-*/%".contains(command)) {
operator = command;
num1 = Double.parseDouble(display.getText());
display.setText("");
} else {
// Handle number buttons
display.setText(display.getText() + command);
}
break;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
SimpleCalculator calculator = new SimpleCalculator();
calculator.setVisible(true);
});
}
}
OUTPUT
Result
Thus, the java program to implement a simple calculator and use a grid layout to arrange
buttons for the digits and operations, add a text field to display the result has been created
and executed successfully.
AIM
To write a java program to simulate a traffic light and allow the user to select one of
three lights: red(stop), yellow(ready), or green(go) with radio buttons to implement the
color.
ALGORITHM
Step 1: Start the program.
Step 2: Initialize the JFrame and create a new instance of TrafficLightSimulator.
Step 3: Use a FlowLayout to arrange components vertically.
Step 4: Instantiate a JLabel called messageLabel to display messages related to the traffic
light state.
Step 5: Instantiate three JRadioButton objects: redButton, yellowButton, and greenButton,
each labeled accordingly.
Step 6: Add Action Listeners for each radio button to respond for the user actions
Step 7: Implement the actionPerformed(ActionEvent e) method from the ActionListener
interface..
Step 8: Stop the program.
Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public TrafficLightSimulator() {
// Set up the frame
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Create message label
messageLabel = new JLabel("");
messageLabel.setFont(new Font("Arial", Font.BOLD, 24));
messageLabel.setPreferredSize(new Dimension(250, 50));
add(messageLabel);
@Override
public void actionPerformed(ActionEvent e) {
// Clear previous message
messageLabel.setText("");
OUTPUT
Result
Thus, the java program to simulate a traffic light and allow the user to select one of three
lights: red(stop), yellow(ready), or green(go) with radio buttons to implement the color has
een created and executed successfully.