0% found this document useful (0 votes)
15 views51 pages

Java Lab Program COPY2

The document contains multiple Java programs demonstrating various functionalities including prime number generation, matrix multiplication, string manipulation, random number generation, and multi-threading. Each section includes an algorithm, source code, and a note indicating successful execution. The programs cover fundamental programming concepts and operations in Java.

Uploaded by

nk3182006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
15 views51 pages

Java Lab Program COPY2

The document contains multiple Java programs demonstrating various functionalities including prime number generation, matrix multiplication, string manipulation, random number generation, and multi-threading. Each section includes an algorithm, source code, and a note indicating successful execution. The programs cover fundamental programming concepts and operations in Java.

Uploaded by

nk3182006
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 51

1.

Write a Java program that prompts the user for an integer and then
prints out all the prime numbers up to that Integer

Algorithm:
1. Start.
2. Initialize variables i, j, n, s = 0.
3. Read input n from the user.
4. Print headers for prime numbers.
5. Loop i from 2 to n.
6. Set s = 0.
7. Loop j from 2 to i/2.
8. If i % j == 0, set s = 1 and break.
9. If s == 0, print i.
10. End.
Source Code:
import java.io.*;
class prime
{
public static void main(String args[])
{
try
{
InputStreamReader n1 = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(n1);
int i,j,n, s =0;
System.out.println( "PRIME NUMBER");
System.out.print( "GIVEN NUMBER IS =");
n = Integer.parseInt(br.readLine());
System.out.println ("PRIME NUMBERS:");
for (i = 2; i <= n; i++)
{
s = 0;
for (j = 2; j <= i/2; j++)
{
if (i % j == 0)
{
s++;
break;
}
}
if (s == 0)
System.out.println (i);
}
}catch(Exception e){}
}
}

OUTPUT:

Result: The Program was successfully executed


2. Write a Java program to multiply two given matrices.

Algorithm
1. Start
2. Accept two matrices, A and B, as input.
3. Check if the number of columns in matrix A is equal to the number of
rows in matrix B:
4. If not equal, print an error message indicating that the matrices cannot
be multiplied.
5. If equal, continue to the next step.
6. Create an empty result matrix, C, with dimensions (number of rows in A)
x (number of columns in B).
7. Iterate through each row i of matrix A:
8. Iterate through each column j of matrix B:
9. Initialize the element c_ij of matrix C to 0.
10. Iterate through each element k of row i of matrix A and column j of
matrix B:
11. Multiply the corresponding elements from matrices A and B: A[i][k] *
B[k][j].
12. Add the result to c_ij.
13. Repeat step 5 for all elements of matrix C.
14. Print matrix C, which is the result of multiplying matrices A and B.
15. End
Source Code:
public class Matmul
{
public static void main(String args[])
{
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int c[][]=new int[3][3];

for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
}//end of j loop
System.out.println();//new line
}
}
}
OUTPUT:

Result: The Program was successfully executed


Write a Java program to add two given matrices.
public class Matadd
{
public static void main(String args[])
{
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int c[][]=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
c[i][j]=a[i][j]+b[i][j];

System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output:
3. Java program that displays the number of characters, lines and words in
a text

Algorithm:
1. Start.
2. Initialize cc = 0, wc = 0, lc = 0.
3. Create BufferedReader to read input.
4. Print message to enter text (stop at "END").
5. Loop to read lines from input.
6. If line is "END", break the loop.
7. Increment lc (line count).
8. Add line length to cc (character count).
9. Use StringTokenizer to count words and add to wc.
10. Print line, word, and character counts.
11. End.
Source Code:
import java.io.*;
import java.util.StringTokenizer;

public class TextAnalyzer {


public static void main(String args[])
{
try
{
InputStreamReader n1 = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(n1);
System.out.println("Enter text (type 'END' on a new line to finish):");
int cc = 0;
int wc = 0;
int lc = 0;
String line;
while ((line = br.readLine()) != null) {
if (line.equalsIgnoreCase("END")) {
break;
}

lc++;
cc += line.length();

// Count words using StringTokenizer


StringTokenizer tokenizer = new StringTokenizer(line);
wc += tokenizer.countTokens();
}
System.out.println("\nAnalysis:");
System.out.println("Number of lines: " + lc);
System.out.println("Number of words: " + wc);
System.out.println("Number of characters: " + cc);
} catch (Exception e) { }
}
}
Output:

Result: The Program was successfully executed


4. Java Program to generate random numbers between two given limits using
Random class and print messages according to the range of the value
generated

Algorithm:
1. Start
2. Define the lower and upper limits for generating random numbers.
3. Create an instance of the Random class.
4. Generate a random number between the lower and upper limits using
the nextInt() method of the Random class.
5. Print the generated random number.
6. Check the generated random number:
7. If the random number is less than 20:
8. Print a message indicating that the generated number is less than 20.
9. If the random number is between 20 and 29:
10. Print a message indicating that the generated number is between 20 and
29.
11. If the random number is 30 or greater:
12. Print a message indicating that the generated number is 30 or greater.
13. End
Source Code:
import java.util.Random;
public class RandomNumberGenerator4 { public static void main(String[] args) {
// Define the lower and upper limits int lowerLimit = 10;
int upperLimit = 50;
// Create an instance of the Random class Random random = new Random();
// Generate a random number between the lower and upper limits
int randomNumber = random.nextInt(upperLimit - lowerLimit + 1) + lowerLimit;
// Print the generated random number
System.out.println("Generated Random Number: " + randomNumber);
// Print message according to the range of the generated number if
(randomNumber < 20) {
System.out.println("Generated number is less than 20");
} else if (randomNumber >= 20 && randomNumber < 30) {
System.out.println("Generated number is between 20 and 29");
} else {
System.out.println("Generated number is 30 or greater");
}
}
}

OUTPUT:

Result: The Program was successfully executed


5. Java program to do String Manipulation using Character Array and perform
the following string operations: String length, Find Character and concatenate
two strings

Algorithm:
1. Start
2. Create BufferedReader for input.
3. Prompt and read str1 (first string).
4. Prompt and read str2 (second string).
5. Print the length of str1.
6. Print the length of str2.
7. Prompt for a position to find a character in str1.
8. Read and convert position input to integer.
9. If position is valid, print the character at that position.
10. If position is invalid, print an error message.
11. Concatenate str1 and str2 and print the result.
12. End.
Source Code
Import java.io.*;
public class strmanip {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

// Input the first string


System.out.print("Enter the first string: ");
String str1 = br.readLine();

// Input the second string


System.out.print("Enter the second string: ");
String str2 = br.readLine();

// Calculate lengths and display


System.out.println("\nLength of the first string: " + str1.length());
System.out.println("Length of the second string: " + str2.length());

// Find character at a given position


System.out.print("\nEnter the position to find the character in the first
string (0-indexed): ");
int position = Integer.parseInt(br.readLine());

if (position >= 0 && position < str1.length()) {


System.out.println("Character at position " + position + " in the first
string: " + str1.charAt(position));
} else {
System.out.println("Invalid position!");
}

// Concatenate and display the result


System.out.println("\nConcatenated string: " + str1 + str2);
}
}

OUTPUT:
6. Java program to perform the following string operations using String
class: String Concatenation, Search String and Extract String

Algorithm:
1. Start
2. Create a Scanner object for input.
3. Prompt and read str1 (first string).
4. Prompt and read str2 (second string).
5. Concatenate str1 and str2, then print the result.
6. Prompt and read mainString (string for substring search).
7. Prompt and read subString (substring to search).
8. Check if subString is present in mainString and print the result.
9. Prompt and read originalString (string for index-based extraction).
10. Prompt and read startIndex.
11. Prompt and read endIndex.
12. Extract substring from originalString using indices and print the result.
13. Close the Scanner.
14. End.
Source Code:
import java.util.Scanner;
public class UserStringOperations { public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking input strings from the user System.out.println("Enter the first
string:"); String str1 = scanner.nextLine(); System.out.println("Enter the second
string:"); String str2 = scanner.nextLine();
// String Concatenation
String concatenatedString = str1.concat(str2);
System.out.println("Concatenated String: " + concatenatedString);
// Search a substring System.out.println("Enter a new string:"); String
mainString = scanner.nextLine();
System.out.println("Enter the substring to search:"); String subString =
scanner.nextLine();
boolean isSubstringPresent = mainString.contains(subString); if
(isSubstringPresent) {
System.out.println("Substring '" + subString + "' found in the main string.");
} else {
System.out.println("Substring '" + subString + "' not found in the main string.");
}
// To extract substring from given string
System.out.println("Enter the main string to be searched according to index
positions:"); String originalString = scanner.nextLine();
System.out.println("Enter the start index:"); int startIndex = scanner.nextInt();
System.out.println("Enter the end index:");
int endIndex = scanner.nextInt();
String extractedSubstring = originalString.substring(startIndex, endIndex);
System.out.println("Extracted Substring: " + extractedSubstring);
scanner.close();
}
}

OUTPUT:

Result: The Program was successfully executed


7. Java program to perform string operations using StringBufferclass: Length
of a String, Reverse a string and Delete a substring

Algorithm:
1. Start
2. Create BufferedReader for input.
3. Prompt and read input string.
4. Create StringBuffer object sb with input.
5. Calculate and print the length of the string.
6. Reverse and print the string.
7. Reverse back to restore the original string.
8. Prompt and read startIndex for deletion.
9. Prompt and read endIndex for deletion.
10. If indices are valid, delete the substring and print the modified string.
11. If indices are invalid, print an error message.
12. End.
Source code:
import java.io.*;
public class strbufopn {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Input the string
System.out.print("Enter a string: ");
String input = br.readLine();
StringBuffer sb = new StringBuffer(input);
// a) Length of the string
int length = sb.length();
System.out.println("Length of the string: " + length);
// b) Reverse the string
System.out.println("Reversed string: " + sb.reverse());
sb.reverse(); // Revert back to the original string
// c) Delete a substring from the string
System.out.print("Enter the start index of the substring to delete: ");
int startIndex = Integer.parseInt(br.readLine());
System.out.print("Enter the end index of the substring to delete: ");
int endIndex = Integer.parseInt(br.readLine());
if (startIndex >= 0 && endIndex <= sb.length() && startIndex < endIndex) {
sb.delete(startIndex, endIndex);
System.out.println("String after deletion: " + sb);
} else {
System.out.println("Invalid indices for deletion!");
}
}
}
8. Java program that implements a multi-thread application to generate
random integer, square of even numbers and cube of odd numbers

Algorithm:
1. Start
2. Create RandomNumberGenerator class implementing Runnable.
3. Inside run() method:
4. Create Random object.
5. Enter an infinite loop:
6. Sleep for 1 second.
7. Generate a random number (0-99).
8. Print the generated number.
9. If the number is even, call SquareThread.square().
10. If the number is odd, call CubeThread.cube().
11. Create SquareThread class with square() method to print the square of a
number.
12. Create CubeThread class with cube() method to print the cube of a
number.
13. In MultiThreadApplication class:
14. Create a thread for RandomNumberGenerator.
15. Start the thread.
16. End.
Source Code:
import java.util.Random;
class RandomNumberGenerator implements Runnable
{ @Override
public void run() {
Random random = new Random(); while (true) {
try {
Thread.sleep(1000);
int randomNumber = random.nextInt(100); System.out.println("Generated
Number: " + randomNumber); if (randomNumber % 2 == 0) {
SquareThread.square(randomNumber);
} else {
CubeThread.cube(randomNumber);
}
} catch (InterruptedException e) { e.printStackTrace();
}
}
}
}
class SquareThread {
public static void square(int number) { System.out.println("Square: " + (number
* number));
}
}
class CubeThread {
public static void cube(int number) {
System.out.println("Cube: " + (number * number * number));
}
}
public class MultiThreadApplication { public static void main(String[] args) {
Thread generatorThread = new Thread(new RandomNumberGenerator());
generatorThread.start();
}
}

OUTPUT:

Result: The Program was successfully executed


9. Write a threading program which uses the same method asynchronously to
print the numbers 1 to 10 using Thread1 and to print 90 to 100 using Thread2.

Algorithm:
1. Start
2. Define NumberPrinter class implementing Runnable.
3. Create NumberPrinter constructor with start and end values.
4. Implement run() method to print numbers from start to end.
5. In Main class, create NumberPrinter instance printer1 for range 1-10.
6. Create NumberPrinter instance printer2 for range 90-100.
7. Create Thread1 with printer1.
8. Create Thread2 with printer2.
9. Start Thread1.
10. Start Thread2.
11. End.
Source Code:
class NumberPrinter implements Runnable { private final int start;
private final int end;
public NumberPrinter(int start, int end) { this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
public class Main {
public static void main(String[] args) {
// Create instances of the NumberPrinter for Thread1 and Thread2
NumberPrinter printer1 = new NumberPrinter(1, 10); NumberPrinter printer2 =
new NumberPrinter(90, 100);
// Create threads for Thread1 and Thread2
Thread thread1 = new Thread(printer1, "Thread1"); Thread thread2 = new
Thread(printer2, "Thread2");
// Start the threads thread1.start(); thread2.start();
}}
OUTPUT

Result: The Program was successfully executed


10. Java program to demonstrate the use of following exceptions : Arithmetic
, Number Format, Array Index out of Bound and Negative Array Size
Exceptions

Algorithm:

1. Start
2. Handle Arithmetic Exception:
o Try to divide a number by zero.
o If an exception occurs, catch it and display
"ArithmeticException: Cannot divide by zero."
3. Handle Number Format Exception:
o Try to convert an invalid string ("ABC") to an integer.
o If an exception occurs, catch it and display
"NumberFormatException: Invalid number
format."
4. Handle Array Index Out of Bounds Exception:
o Declare an integer array with some elements.
o Try to access an invalid index (out of array bounds).
o If an exception occurs, catch it and display
"ArrayIndexOutOfBoundsException: Index out of
range."
5. Handle Negative Array Size Exception:
o Try to create an array with a negative size.
o If an exception occurs, catch it and display
"NegativeArraySizeException: Array size
cannot be negative."
6. End
Source Code
public class ExceptionDemo {
public static void main(String[] args) {
// 1. ArithmeticException
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: Cannot divide by zero.");
}

// 2. NumberFormatException
try {
int num = Integer.parseInt("ABC"); // Invalid number conversion
} catch (NumberFormatException e) {
System.out.println("NumberFormatException: Invalid number format.");
}

// 3. ArrayIndexOutOfBoundsException
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // Accessing out of bounds index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException: Index out of
range.");
}

// 4. NegativeArraySizeException
try {
int[] arr = new int[-5]; // Negative size array
} catch (NegativeArraySizeException e) {
System.out.println("NegativeArraySizeException: Array size cannot be
negative.");
}
}
}

OUTPUT:
ArithmeticException: Cannot divide by zero.
NumberFormatException: Invalid number format.
ArrayIndexOutOfBoundsException: Index out of range.
NegativeArraySizeException: Array size cannot be negative.
11. Wite a Java program that reads on file name from the user, then displays
information whether the file exists, is readable, is writable, the type of file
and the length of the file in bytes.

Algorithm :

1. Start
2. Print "Please enter the file name:"
3. Read inputFileName from the user
4. Check if the file exists:
5. If file exists:
6. Print "File exists." Check file permissions:
7. Check if the file is readable:
8. If true, Print "File is readable." Else, Print "File is not readable."
9. Check if the file is writable:
10. if true, Print "File is writable." Else, Print "File is not writable."
11. Get the type of the file:
12. Use system functions to determine the file type
13. Print the file type
14. Get the length of the file:
15. Use system functions to get the length of the file
16. Print the length of the file in bytes
17. If file doesn't exist:
18. Print "File does not exist."
19. End
Source Code:
import java.io.File; import java.util.Scanner; public class FileInfo {
public static void main(String[] args) { Scanner scanner = new
Scanner(System.in);
// Prompt user to enter the file name System.out.println("Enter the file
name:"); String fileName = scanner.nextLine();
// Create a File object with the given file name File file = new File(fileName);
// Check if the file exists if (file.exists()) {
System.out.println("File exists: Yes");

// Check if the file is readable


System.out.println("File readable: " + (file.canRead() ? "Yes" : "No"));

// Check if the file is writable


System.out.println("File writable: " + (file.canWrite() ? "Yes" : "No"));

// Determine the type of file if (file.isFile()) {


System.out.println("File type: Regular file");
} else if (file.isDirectory()) { System.out.println("File type: Directory");
}
// Display the length of the file in bytes System.out.println("File length (bytes): "
+ file.length());
} else {
System.out.println("File does not exist.");
}
scanner.close();
}
}

OUTPUT:

Result: The Program was successfully executed


12. Java program to accept a text and change its size and font including bold
italic options with frames and controls.

Algorithm:

Algorithm for TextEditor

1. Initialize Frame
o Create a JFrame with title, size, and close operation.
2. Create Components
o JTextArea for text input.

o JScrollPane for scrolling.

o JComboBox for font size selection.

o JCheckBox for bold and italic styles.


3. Set Default Font
o Set default font size to 12.
4. Add Action Listeners
o FontSizeListener: Changes font size based on selection.

o FontStyleListener: Updates font style when bold or italic is


selected.
5. Create Control Panel
o Add label, font size dropdown, and checkboxes.
6. Add Components to Frame
o Place control panel at the top (NORTH).

o Place text area in the center (CENTER).


7. Run Program
o Use SwingUtilities.invokeLater() to create an
instance of TextEditor.
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TextEditor extends JFrame { private JTextArea textArea;
private JComboBox<String> fontSizeCombo; private JCheckBox boldCheckBox;
private JCheckBox italicCheckBox;
public TextEditor() { setTitle("Text Editor"); setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Create components textArea = new JTextArea();
JScrollPane scrollPane = new JScrollPane(textArea);
String[] fontSizeOptions = {"8", "10", "12", "14", "16", "18", "20", "22", "24",
"26", "28", "30"};
fontSizeCombo = new JComboBox<>(fontSizeOptions); boldCheckBox = new
JCheckBox("Bold"); italicCheckBox = new JCheckBox("Italic");
// Set default font size fontSizeCombo.setSelectedIndex(2);
// Add action listeners fontSizeCombo.addActionListener(new
FontSizeListener()); boldCheckBox.addActionListener(new FontStyleListener());
italicCheckBox.addActionListener(new FontStyleListener());
// Create panel for controls
JPanel controlPanel = new JPanel(); controlPanel.setLayout(new FlowLayout());
controlPanel.add(new JLabel("Font Size:")); controlPanel.add(fontSizeCombo);
controlPanel.add(boldCheckBox); controlPanel.add(italicCheckBox);

// Add components to frame add(controlPanel, BorderLayout.NORTH);


add(scrollPane, BorderLayout.CENTER); setVisible(true);
}
class FontSizeListener implements ActionListener { @Override
public void actionPerformed(ActionEvent e) {
String selectedSize = (String) fontSizeCombo.getSelectedItem(); int size =
Integer.parseInt(selectedSize);
Font font = textArea.getFont().deriveFont(Font.PLAIN, size);
textArea.setFont(font);
}
}
class FontStyleListener implements ActionListener { @Override
public void actionPerformed(ActionEvent e) { int style = Font.PLAIN;
if (boldCheckBox.isSelected()) { style += Font.BOLD;
}
if (italicCheckBox.isSelected()) {
style += Font.ITALIC;
}
Font font = textArea.getFont().deriveFont(style); textArea.setFont(font);
}
}
public static void main(String[] args) { SwingUtilities.invokeLater(() -> new
TextEditor());
}
}
OUTPUT:

Result: The Program was successfully executed


13. Java program that handles all mouse events and shows the event name at
the center of the window when a mouse event is fired using adapter classes

Algorithm

1. Initialize Frame
o Create a Frame and set title, size, and visibility.
2. Implement Mouse Listener
o Use MouseAdapter to override mouse event methods:

 mousePressed → Set event name to "Mouse Pressed"


and repaint.
 mouseReleased → Set event name to "Mouse Released"
and repaint.
 mouseClicked → Set event name to "Mouse Clicked" and
repaint.
 mouseEntered → Set event name to "Mouse Entered"
and repaint.
 mouseExited → Set event name to "Mouse Exited" and
repaint.
3. Paint Event Name
o Override paint(Graphics g).

o Get FontMetrics to center the text.


o Draw the event name in the center.
4. Run Program
o Call main() to create an instance of MouseEventDemo.
Code:
import java.awt.*; import java.awt.event.*;
class MouseEventDemo extends Frame { private String eventName;

public MouseEventDemo() { eventName = "";


addMouseListener(new MouseAdapter() { @Override
public void mousePressed(MouseEvent e) { eventName = "Mouse Pressed";
repaint();
}
@Override
public void mouseReleased(MouseEvent e) { eventName = "Mouse Released";
repaint();
}
@Override
public void mouseClicked(MouseEvent e) { eventName = "Mouse Clicked";
repaint();
}
@Override
public void mouseEntered(MouseEvent e) { eventName = "Mouse Entered";
repaint();
}
@Override
public void mouseExited(MouseEvent e) { eventName = "Mouse Exited";
repaint();
}
});
setSize(400, 300); setTitle("Mouse Events Demo"); setVisible(true);
}
@Override
public void paint(Graphics g) { super.paint(g);
FontMetrics fm = g.getFontMetrics();
int textWidth = fm.stringWidth(eventName); int textHeight = fm.getHeight();
int centerX = (getWidth() - textWidth) / 2; int centerY = (getHeight() +
textHeight) / 2; g.drawString(eventName, centerX, centerY);
}
public static void main(String[] args) { new MouseEventDemo();
}
}
OUTPUT

Result: The Program was successfully executed


14. Java program that works as a simple calculator using a grid layout to
arrange buttons for the digits and for the +, -,*, % operations and to handle
divide by zero exception.

Algorithm

1. Initialize Frame
o Create a JFrame with title, layout, and close operation.
o Add a JTextField for displaying input/output (non-editable).
2. Create Buttons
o Create digit buttons (0-9) and add action listeners.
o Create operator buttons (+, -, *, /, %, =) and add action listeners.
o Arrange buttons in a JPanel using GridLayout.
3. Handle Button Clicks (actionPerformed)
o If a digit is clicked, update currentInput and display it.
o If an operator (+, -, *, /, %) is clicked:
 Perform the previous calculation (if applicable).
 Store the operator for the next calculation.
 Set isNewInput to true for new entry.
o If = is clicked, perform the calculation and display the result.
4. Perform Calculations (calculate)
o Convert currentInput to a number.
o Perform the operation based on operator.
o Handle division by zero error.
o Update the display with the result.
5. Reset Calculator (reset)
o Set currentInput to an empty string.
o Initialize result to 0 and operator to a space.
o Set textField display to "0".
6. Run Program
o Create an instance of SimpleCalculator in main().
Source Code:
import java.awt.*;
import java.awt.event.*; i
mport javax.swing.*;
public class SimpleCalculator extends JFrame implements ActionListener {
private JTextField textField;
private JButton[] digitButtons;
private JButton addButton, subtractButton, multiplyButton, divideButton,
modulusButton, equalsButton;
private String currentInput; private double result; private char operator; private
boolean isNewInput; public SimpleCalculator() {
setTitle("Simple Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new
BorderLayout());
textField = new JTextField(); textField.setEditable(false); add(textField,
BorderLayout.NORTH);

JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(4, 4,


5, 5)); digitButtons = new JButton[10];
for (int i = 0; i < 10; i++) {
digitButtons[i] = new JButton(String.valueOf(i));
digitButtons[i].addActionListener(this); buttonPanel.add(digitButtons[i]);
}
addButton = new JButton("+");
addButton.addActionListener(this); buttonPanel.add(addButton);
subtractButton = new JButton("-"); subtractButton.addActionListener(this);
buttonPanel.add(subtractButton); multiplyButton = new JButton("*");
multiplyButton.addActionListener(this); buttonPanel.add(multiplyButton);
divideButton = new JButton("/"); divideButton.addActionListener(this);
buttonPanel.add(divideButton);

modulusButton = new JButton("%"); modulusButton.addActionListener(this);


buttonPanel.add(modulusButton); equalsButton = new JButton("=");
equalsButton.addActionListener(this); buttonPanel.add(equalsButton);
add(buttonPanel, BorderLayout.CENTER); pack();
setLocationRelativeTo(null); setVisible(true);
reset();
}
private void reset() { currentInput = ""; result = 0; operator = ' '; isNewInput =
true;
textField.setText("0");
}
private void calculate() { try {
double input = Double.parseDouble(currentInput); switch (operator) {
case '+':
result += input; break;
case '-':
result -= input; break;
case '*':
result *= input; break;
case '/':
if (input == 0) {
throw new ArithmeticException("Cannot divide by zero!");
}
result /= input; break;
case '%':
result %= input; break;
default:
result = input;
}
textField.setText(String.valueOf(result));
} catch (NumberFormatException e) { textField.setText("Error");
} catch (ArithmeticException e) { textField.setText("Cannot divide by zero!");
}
}
@Override
public void actionPerformed(ActionEvent e) { String command =
e.getActionCommand(); if (Character.isDigit(command.charAt(0))) {
if (isNewInput) { currentInput = ""; isNewInput = false;
}
currentInput += command; textField.setText(currentInput);
} else if (command.charAt(0) == '=') { calculate();
isNewInput = true;
} else {
if (!isNewInput) { calculate();
}
operator = command.charAt(0); isNewInput = true;
}
}
public static void main(String[] args) { new SimpleCalculator();
}
}
OUTPUT:

Result: The Program was successfully executed


15. Java program that simulates a traffic light.

Algorithm:

1. Initialize Frame
o Create a JFrame with a title, layout, and close operation.
2. Create Radio Buttons
o Create three JRadioButtons for "Red", "Yellow", and "Green".

o Group the buttons using a ButtonGroup to ensure only one is


selected at a time.
o Add action listeners to each button.
3. Create Message Label
o Create a JLabel for displaying the traffic signal message.
o Set font and alignment properties.
4. Add Components to Frame
o Add radio buttons to a JPanel and place them at the center.
o Add the message label at the top.
o Set the frame properties (pack, center, and make visible).
5. Handle Button Clicks (actionPerformed)
o Check which radio button is selected.

o Update the messageLabel text and color accordingly:

 Red → "Stop" (Red color)

 Yellow → "Ready" (Yellow color)

 Green → "Go" (Green color)


6. Run Program
o Create an instance of TrafficLightSimulator using

SwingUtilities.invokeLater().

Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TrafficLightSimulator extends JFrame implements ActionListener {
private JRadioButton redButton, yellowButton, greenButton;
private ButtonGroup buttonGroup; private JLabel messageLabel; public
TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new
BorderLayout());
redButton = new JRadioButton("Red"); yellowButton = new
JRadioButton("Yellow"); greenButton = new JRadioButton("Green");

buttonGroup = new ButtonGroup(); buttonGroup.add(redButton);


buttonGroup.add(yellowButton); buttonGroup.add(greenButton);

redButton.addActionListener(this); yellowButton.addActionListener(this);
greenButton.addActionListener(this); JPanel radioPanel = new JPanel();
radioPanel.add(redButton); radioPanel.add(yellowButton);
radioPanel.add(greenButton); add(radioPanel, BorderLayout.CENTER);
messageLabel = new JLabel();
messageLabel.setHorizontalAlignment(SwingConstants.CENTER);
messageLabel.setFont(new Font("Arial", Font.BOLD, 18)); add(messageLabel,
BorderLayout.NORTH);
pack(); setLocationRelativeTo(null); setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) { String message = "";
Color color = Color.BLACK;
if (e.getSource() == redButton) { message = " Stop";
color = Color.RED;
} else if (e.getSource() == yellowButton) { message = "Ready";
color = Color.YELLOW;
} else if (e.getSource() == greenButton) { message = "Go";
color = Color.GREEN;
}
messageLabel.setText(message); messageLabel.setForeground(color);
}
public static void main(String[] args) { SwingUtilities.invokeLater(new
Runnable() {
public void run() {
new TrafficLightSimulator();
}
});
}
}
OUTPUT:

Result: The Program was successfully executed

You might also like