/* Java program that prompts the user for an integer and then prints Out all the prime
numbers up to that Integer*/
import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.println("Prime numbers up to " + number + " are:");
for (int i = 2; i <= number; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
DEPARTMENT OF COMPUTER SCIENCE
OUTPUT
Enter a number: 10
Prime numbers up to 10 are:
2357
DEPARTMENT OF COMPUTER SCIENCE
// Java program to multiply two given matrices
public class MultiplyMatrices {
public static void main(String[] args) {
int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;
int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };
int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} };
// Mutliplying Two matrices
int[][] product = new int[r1][c2];
for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}
// Displaying the result
System.out.println("Multiplication of two matrices is: ");
for(int[] row : product) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}
DEPARTMENT OF COMPUTER SCIENCE
Output
Multiplication of two matrices is:
24 29
6 25
DEPARTMENT OF COMPUTER SCIENCE
/* Java program that displays the number of characters, lines and words in a text. */
import java.util.Scanner;
public class TextAnalyzer {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the text (type 'exit' to end input):");
// Initialize variables to store the number of characters, words, and lines
int charCount = 0;
int wordCount = 0;
int lineCount = 0;
// Read the input line by line until the user types 'exit'
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
// Exit the loop if the user types 'exit'
if (line.equalsIgnoreCase("exit")) {
break;
}
// Increment line count
lineCount++;
// Count the characters in the line
charCount += line.length();
// Split the line into words and count them
String[] words = line.split("\\s+");
wordCount += words.length;
}
// Display the results
System.out.println("Number of characters: " + charCount);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of lines: " + lineCount);
}
}
DEPARTMENT OF COMPUTER SCIENCE
OUTPUT
Enter the text (type 'exit' to end input):
Enter text (type 'exit' on a new line to stop):
hello
welcome to java
exit
Statistics:
Number of Lines: 2
Number of Words: 4
Number of Characters: 20
C:\Users\ADMIN\Desktop\java>
DEPARTMENT OF COMPUTER SCIENCE
/ * Generate random numbers between two given limits using Random class and print
messages according to the range of the value generated. */
import java.util.Random;
import java.util.Scanner;
public class RandomNumberRange {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner scanner = new Scanner(System.in);
// Create a Random object for generating random numbers
Random random = new Random();
// Get the lower and upper limits from the user
System.out.print("Enter the lower limit: ");
int lowerLimit = scanner.nextInt();
System.out.print("Enter the upper limit: ");
int upperLimit = scanner.nextInt();
// Check if lower limit is less than upper limit
if (lowerLimit >= upperLimit) {
System.out.println("Invalid limits. The lower limit must be less than the upper limit.");
return;
}
// Generate a random number between the given limits
int randomNumber = random.nextInt(upperLimit - lowerLimit + 1) + lowerLimit;
// Print the random number and message according to its range
System.out.println("Generated Random Number: " + randomNumber);
if (randomNumber < lowerLimit + (upperLimit - lowerLimit) / 3) {
System.out.println("The number is in the lower range.");
} else if (randomNumber < lowerLimit + 2 * (upperLimit - lowerLimit) / 3) {
System.out.println("The number is in the middle range.");
} else {
System.out.println("The number is in the higher range.");
}
}
}
DEPARTMENT OF COMPUTER SCIENCE
OUTPUT
Enter the lower limit: 10
Enter the upper limit: 50
Generated Random Number: 27
The number is in the middle range.
DEPARTMENT OF COMPUTER SCIENCE
/* Java program to do String Manipulation using Character Array and perform the
following string operations:
a. String length
b. Finding a character at a particular position
c. Concatenating two strings */
import java.util.Scanner;
public class StringManipulationUsingCharArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the first string:");
String firstString = scanner.nextLine();
System.out.println("Enter the second string:");
String secondString = scanner.nextLine();
// Convert strings to character arrays
char[] firstCharArray = firstString.toCharArray();
char[] secondCharArray = secondString.toCharArray();
// 1. Calculate string length
int lengthOfFirstString = firstCharArray.length;
int lengthOfSecondString = secondCharArray.length;
System.out.println("\nLength of first string: " + lengthOfFirstString);
System.out.println("Length of second string: " + lengthOfSecondString);
// 2. Find a character at a particular position
System.out.print("\nEnter the position (index) to find a character in the first string: ");
int position = scanner.nextInt();
if (position >= 0 && position < firstCharArray.length) {
System.out.println("Character at position " + position + " in the first string: " +
firstCharArray[position]);
} else {
System.out.println("Invalid position for the first string.");
}
// 3. Concatenate two strings
char[] concatenatedArray = new char[firstCharArray.length + secondCharArray.length];
// Copy first string into the concatenated array
System.arraycopy(firstCharArray, 0, concatenatedArray, 0, firstCharArray.length);
DEPARTMENT OF COMPUTER SCIENCE
// Copy second string into the concatenated array
System.arraycopy(secondCharArray, 0, concatenatedArray, firstCharArray.length,
secondCharArray.length);
// Convert concatenated character array back to a string
String concatenatedString = new String(concatenatedArray);
System.out.println("\nConcatenated string: " + concatenatedString);
scanner.close();
}
}
DEPARTMENT OF COMPUTER SCIENCE
OUTPUT
C:\Users\ADMIN\Desktop\java>javac StringManipulationUsingCharArray.java
C:\Users\ADMIN\Desktop\java>java StringManipulationUsingCharArray
Enter the first string:
welcome
Enter the second string:
java
Length of first string: 7
Length of second string: 4
Enter the position (index) to find a character in the first string: 2
Character at position 2 in the first string: l
Concatenated string: welcomejava
C:\Users\ADMIN\Desktop\java>
DEPARTMENT OF COMPUTER SCIENCE
/* Java program to perform the following string operations using String class:
a. String Concatenation
b. Search a substring
c. To extract substring from given string*/
import java.util.Scanner;
public class StringOperationsUsingStringClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input two strings
System.out.println("Enter the first string:");
String firstString = scanner.nextLine();
System.out.println("Enter the second string:");
String secondString = scanner.nextLine();
// String Concatenation
String concatenatedString = firstString + secondString;
System.out.println("\nConcatenated String: " + concatenatedString);
// Search a substring
System.out.println("\nEnter the substring to search:");
String substringToSearch = scanner.nextLine();
if (firstString.contains(substringToSearch)) {
System.out.println("The substring '" + substringToSearch + "' is found in the first string.");
} else {
System.out.println("The substring '" + substringToSearch + "' is not found in the first string.");
}
// To extract substring
System.out.print("\nEnter the starting index to extract a substring: ");
int startIndex = scanner.nextInt();
// To handle user input and valid range for substring
scanner.nextLine(); // consume the newline character after nextInt
System.out.print("Enter the ending index (exclusive) to extract a substring: ");
int endIndex = scanner.nextInt();
// Check if the indices are valid
if (startIndex >= 0 && endIndex <= firstString.length() && startIndex < endIndex) {
String extractedSubstring = firstString.substring(startIndex, endIndex);
DEPARTMENT OF COMPUTER SCIENCE
System.out.println("\nExtracted Substring: " + extractedSubstring);
} else {
System.out.println("Invalid indices for substring extraction.");
}
scanner.close();
}
}
DEPARTMENT OF COMPUTER SCIENCE
OUTPUT
C:\Users\ADMIN\Desktop\java>javac StringOperationsUsingStringClass.java
C:\Users\ADMIN\Desktop\java>java StringOperationsUsingStringClass
Enter the first string:
hello
Enter the second string:
India
Concatenated String: helloIndia
Enter the substring to search:
llo
The substring 'llo' is found in the first string.
Enter the starting index to extract a substring: 1
Enter the ending index (exclusive) to extract a substring: 4
Extracted Substring: ell
C:\Users\ADMIN\Desktop\java>
DEPARTMENT OF COMPUTER SCIENCE
/* Java program to perform string operations using StringBuffer class:
a. Length of a string
b. Reverse a string
c. Delete a substring from the given string */
import java.util.Scanner;
public class StringBufferOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input string
System.out.println("Enter a string:");
String inputString = scanner.nextLine();
// Create a StringBuffer from the input string
StringBuffer stringBuffer = new StringBuffer(inputString);
// 1. Find the length of the string
int length = stringBuffer.length();
System.out.println("\nLength of the string: " + length);
// 2. Reverse the string
StringBuffer reversedString = stringBuffer.reverse();
System.out.println("Reversed string: " + reversedString);
// Reverse it back to original for further operations
stringBuffer = new StringBuffer(inputString);
// 3. Delete a substring from the given string
System.out.println("\nEnter the starting index to delete a substring:");
int startIndex = scanner.nextInt();
System.out.println("Enter the ending index (exclusive) to delete a substring:");
int endIndex = scanner.nextInt();
// Validate indices
if (startIndex >= 0 && endIndex <= stringBuffer.length() && startIndex < endIndex) {
stringBuffer.delete(startIndex, endIndex);
System.out.println("\nString after deletion: " + stringBuffer);
} else {
System.out.println("Invalid indices for deletion.");
}
scanner.close();
}
}
DEPARTMENT OF COMPUTER SCIENCE
OUTPUT
DEPARTMENT OF COMPUTER SCIENCE
Enter a string:
Hello, World!
Length of the string: 13
Reversed string: !dlroW ,olleH
Enter the starting index to delete a substring:
7
Enter the ending index (exclusive) to delete a substring:
12
String after deletion: Hello,
DEPARTMENT OF COMPUTER SCIENCE
// Java Program that implements multithread operation
import java.util.Random;
import java.lang.*;
class Square extends Thread
{
int x;
Square(int n)
{
x = n;
}
public void run()
{
int sqr = x * x;
System.out.println("Square of " + x + " = " + sqr );
}
}
class Cube extends Thread
{
int x;
Cube(int n)
{
x = n;
}
public void run()
{
int cub = x * x * x;
System.out.println("Cube of " + x + " = " + cub );
}
}
class Number 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);
Square s = new Square(randomInteger);
s.start();
Cube c = new Cube(randomInteger);
c.start();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
System.out.println(ex);
}
DEPARTMENT OF COMPUTER SCIENCE
}
}
}
public class multi {
public static void main(String args[])
{
Number n = new Number();
n.start();
}
}
DEPARTMENT OF COMPUTER SCIENCE
OUTPUT
C:\Users\ADMIN\Desktop\java>javac multi.java
C:\Users\ADMIN\Desktop\java>java multi
Random Integer generated : 75
Square of 75 = 5625
Cube of 75 = 421875
Random Integer generated : 1
Square of 1 = 1
Cube of 1 = 1
Random Integer generated : 76
Square of 76 = 5776
Cube of 76 = 438976
Random Integer generated : 92
Square of 92 = 8464
Cube of 92 = 778688
Random Integer generated : 81
Square of 81 = 6561
Cube of 81 = 531441
Random Integer generated : 85
Square of 85 = 7225
Cube of 85 = 614125
Random Integer generated : 77
Square of 77 = 5929
Cube of 77 = 456533
Random Integer generated : 30
Square of 30 = 900
Cube of 30 = 27000
Random Integer generated : 24
Cube of 24 = 13824
Square of 24 = 576
Random Integer generated : 53
Square of 53 = 2809
Cube of 53 = 148877
/* Write a program to demonstrate the use of following exceptions.
DEPARTMENT OF COMPUTER SCIENCE
Arithmetic Exception
Number Format Exception
Array Index Out of Bound Exception
Negative Array Size Exception */
public class ExceptionDemo {
// Method to demonstrate ArithmeticException
public static void arithmeticExceptionDemo() {
try {
// Dividing by zero to trigger ArithmeticException
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: " + e.getMessage());
}
}
// Method to demonstrate NumberFormatException
public static void numberFormatExceptionDemo() {
try {
// Trying to convert a non-numeric string to an integer
int num = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("Number Format Exception: " + e.getMessage());
}
}
// Method to demonstrate ArrayIndexOutOfBoundsException
public static void arrayIndexOutOfBoundsExceptionDemo() {
try {
// Trying to access an element beyond the array bounds
int[] arr = {1, 2, 3};
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bound Exception: " + e.getMessage());
}
}
// Method to demonstrate NegativeArraySizeException
public static void negativeArraySizeExceptionDemo() {
try {
// Trying to create an array with a negative size
int[] arr = new int[-5];
} catch (NegativeArraySizeException e) {
DEPARTMENT OF COMPUTER SCIENCE
System.out.println("Negative Array Size Exception: " + e.getMessage());
}
}
// Main method to demonstrate all exceptions
public static void main(String[] args) {
System.out.println("Demonstrating ArithmeticException:");
arithmeticExceptionDemo();
System.out.println("\nDemonstrating NumberFormatException:");
numberFormatExceptionDemo();
System.out.println("\nDemonstrating ArrayIndexOutOfBoundsException:");
arrayIndexOutOfBoundsExceptionDemo();
System.out.println("\nDemonstrating NegativeArraySizeException:");
negativeArraySizeExceptionDemo();
}
}
OUTPUT
DEPARTMENT OF COMPUTER SCIENCE
C:\Users\ADMIN\Desktop\java>javac ExceptionDemo.java
C:\Users\ADMIN\Desktop\java>java ExceptionDemo
Demonstrating ArithmeticException:
Arithmetic Exception: / by zero
Demonstrating NumberFormatException:
Number Format Exception: For input string: "abc"
Demonstrating ArrayIndexOutOfBoundsException:
Array Index Out of Bound Exception: Index 5 out of bounds for length 3
Demonstrating NegativeArraySizeException:
Negative Array Size Exception: -5
C:\Users\ADMIN\Desktop\java>
DEPARTMENT OF COMPUTER SCIENCE
/* Write a Java program that reads on file name from the user, then displays information
about 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 */
import java.io.File;
import java.util.Scanner;
public class FileInfo {
public static void main(String[] args) {
// Create a scanner object to read user input
Scanner scanner = new Scanner(System.in);
// Prompt the user to enter the file name
System.out.print("Enter the file name (with path if necessary): ");
String fileName = scanner.nextLine();
// Create a File object using the 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
if (file.canRead()) {
System.out.println("File is readable: Yes");
} else {
System.out.println("File is readable: No");
}
// Check if the file is writable
if (file.canWrite()) {
System.out.println("File is writable: Yes");
} else {
System.out.println("File is writable: No");
}
// Check if the file is a directory or a regular file
if (file.isDirectory()) {
System.out.println("It is a directory.");
} else {
System.out.println("It is a regular file.");
}
// Display the length of the file in bytes
if (file.isFile()) {
System.out.println("File length: " + file.length() + " bytes");
}
DEPARTMENT OF COMPUTER SCIENCE
} else {
System.out.println("File exists: No");
}
// Close the scanner
scanner.close();
}
}
DEPARTMENT OF COMPUTER SCIENCE
OUTPUT
C:\Users\ADMIN\Desktop\java>java FileInfo
Enter the file name (with path if necessary): C:\Users\ADMIN\Desktop\Welcome to Java
File exists: No
C:\Users\ADMIN\Desktop\java>
DEPARTMENT OF COMPUTER SCIENCE
/* Write a program to accept a text and change its size and font. Include bold italic options.
Use frames and controls.*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class FontStyler extends JFrame {
private JTextArea textArea;
private JComboBox<String> fontFamilyComboBox;
private JComboBox<Integer> fontSizeComboBox;
private JCheckBox boldCheckBox;
private JCheckBox italicCheckBox;
public FontStyler() {
// Set the title of the frame
setTitle("Text Font Styler");
setLayout(new BorderLayout());
// Create text area for text input
textArea = new JTextArea(10, 30);
textArea.setFont(new Font("Arial", Font.PLAIN, 14)); // Default font
JScrollPane scrollPane = new JScrollPane(textArea);
add(scrollPane, BorderLayout.CENTER);
// Panel for controls (font family, font size, bold, italic)
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
// Font family dropdown
String[] fontFamilies =
GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
fontFamilyComboBox = new JComboBox<>(fontFamilies);
fontFamilyComboBox.setSelectedItem("Arial"); // Default font family
controlPanel.add(new JLabel("Font Family:"));
controlPanel.add(fontFamilyComboBox);
// Font size dropdown
Integer[] fontSizes = {10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30};
fontSizeComboBox = new JComboBox<>(fontSizes);
fontSizeComboBox.setSelectedItem(14); // Default font size
controlPanel.add(new JLabel("Font Size:"));
controlPanel.add(fontSizeComboBox);
// Bold checkbox
boldCheckBox = new JCheckBox("Bold");
controlPanel.add(boldCheckBox);
// Italic checkbox
DEPARTMENT OF COMPUTER SCIENCE
italicCheckBox = new JCheckBox("Italic");
controlPanel.add(italicCheckBox);
// Add the control panel to the frame
add(controlPanel, BorderLayout.NORTH);
// Action listener for updating font style based on user selection
ActionListener updateFontActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Get selected font family and size
String fontFamily = (String) fontFamilyComboBox.getSelectedItem();
int fontSize = (int) fontSizeComboBox.getSelectedItem();
// Get the current style (bold, italic)
int style = Font.PLAIN;
if (boldCheckBox.isSelected()) style |= Font.BOLD;
if (italicCheckBox.isSelected()) style |= Font.ITALIC;
// Set the new font for the text area
textArea.setFont(new Font(fontFamily, style, fontSize));
}
};
// Add the action listener to the controls
fontFamilyComboBox.addActionListener(updateFontActionListener);
fontSizeComboBox.addActionListener(updateFontActionListener);
boldCheckBox.addActionListener(updateFontActionListener);
italicCheckBox.addActionListener(updateFontActionListener);
// Frame settings
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500, 400);
setVisible(true);
}
public static void main(String[] args) {
// Run the program in the Event-Dispatching Thread (EDT)
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new FontStyler();
}
});
}
}
DEPARTMENT OF COMPUTER SCIENCE
C:\Users\ADMIN\Desktop\java>javac FontStyler.java
C:\Users\ADMIN\Desktop\java>java FontStyler
DEPARTMENT OF COMPUTER SCIENCE
/* Java program that handles all mouse events and shows the event name at the center
of the window when a mouse event is fired.(Use adapter classes). */
import java.awt.*;
import java.awt.event.*;
public class MouseEventExample extends Frame {
// Variable to hold the event name
private String eventName = "No Event";
public MouseEventExample() {
// Set the title of the window
setTitle("Mouse Event Handler");
// Set the layout to null for custom positioning
setLayout(null);
// Set the size of the window
setSize(400, 300);
// Add mouse event listeners using MouseAdapter
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
eventName = "Mouse Clicked";
repaint(); // Requesting a repaint when an event occurs
}
@Override
public void mousePressed(MouseEvent e) {
eventName = "Mouse Pressed";
repaint();
}
@Override
public void mouseReleased(MouseEvent e) {
eventName = "Mouse Released";
repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
eventName = "Mouse Entered";
repaint();
}
@Override
public void mouseExited(MouseEvent e) {
DEPARTMENT OF COMPUTER SCIENCE
eventName = "Mouse Exited";
repaint();
}
});
// Add mouse motion event listeners using MouseAdapter
addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
eventName = "Mouse Dragged";
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
eventName = "Mouse Moved";
repaint();
}
});
// Set the window to be visible
setVisible(true);
// Set the close operation
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0); // Exit the application when the window is closed
}
});
}
// Override the paint method to draw the event name at the center
@Override
public void paint(Graphics g) {
// Get the width and height of the window
Dimension size = getSize();
int width = size.width;
int height = size.height;
// Set the font and draw the event name at the center of the window
g.setFont(new Font("Arial", Font.PLAIN, 20));
FontMetrics metrics = g.getFontMetrics();
int x = (width - metrics.stringWidth(eventName)) / 2; // Center X position
int y = (height + metrics.getHeight()) / 2; // Center Y position
g.drawString(eventName, x, y);
}
public static void main(String[] args) {
DEPARTMENT OF COMPUTER SCIENCE
// Create an instance of MouseEventExample to show the window
new MouseEventExample();
}
}
DEPARTMENT OF COMPUTER SCIENCE
OUTPUT
DEPARTMENT OF COMPUTER SCIENCE
// Java program that works as a simple calculator.
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class calculator extends JFrame implements ActionListener {
// create a frame
static JFrame f;
// create a textfield
static JTextField l;
// store operator and operands
String s0, s1, s2;
// default constructor
calculator()
{
s0 = s1 = s2 = "";
}
// main function
public static void main(String args[])
{
// create a frame
f = new JFrame("calculator");
try {
// set look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.err.println(e.getMessage());
}
// create a object of class
calculator c = new calculator();
// create a textfield
l = new JTextField(16);
// set the textfield to non editable
l.setEditable(false);
// create number buttons and some operators
JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;
DEPARTMENT OF COMPUTER SCIENCE
// create number buttons
b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");
// equals button
beq1 = new JButton("=");
// create operator buttons
ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");
// create . button
be = new JButton(".");
// create a panel
JPanel p = new JPanel();
// add action listeners
bm.addActionListener(c);
bd.addActionListener(c);
bs.addActionListener(c);
ba.addActionListener(c);
b9.addActionListener(c);
b8.addActionListener(c);
b7.addActionListener(c);
b6.addActionListener(c);
b5.addActionListener(c);
b4.addActionListener(c);
b3.addActionListener(c);
b2.addActionListener(c);
b1.addActionListener(c);
b0.addActionListener(c);
be.addActionListener(c);
beq.addActionListener(c);
beq1.addActionListener(c);
// add elements to panel
p.add(l);
DEPARTMENT OF COMPUTER SCIENCE
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);
// set Background of panel
p.setBackground(Color.blue);
// add panel to frame
f.add(p);
f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
// if the value is a number
if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) == '.') {
// if operand is present then add to second no
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;
// set the value of text
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
// clear the one letter
s0 = s1 = s2 = "";
// set the value of text
l.setText(s0 + s1 + s2);
}
DEPARTMENT OF COMPUTER SCIENCE
else if (s.charAt(0) == '=') {
double te;
// store the value in 1st
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
// set the value of text
l.setText(s0 + s1 + s2 + "=" + te);
// convert it to string
s0 = Double.toString(te);
s1 = s2 = "";
}
else {
// if there was no operand
if (s1.equals("") || s2.equals(""))
s1 = s;
// else evaluate
else {
double te;
// store the value in 1st
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
// convert it to string
s0 = Double.toString(te);
// place the operator
s1 = s;
// make the operand blank
s2 = "";
}
DEPARTMENT OF COMPUTER SCIENCE
// set the value of text
l.setText(s0 + s1 + s2);
}
}
}
DEPARTMENT OF COMPUTER SCIENCE
OUTPUT
DEPARTMENT OF COMPUTER SCIENCE
/*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, an appropriate message
with―stop‖or―ready‖or―go‖ should appear above the buttons in a selected color. Initially there is no
message shown */
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TrafficLightSimulator extends JFrame {
// Labels for the messages to be displayed
private JLabel messageLabel;
public TrafficLightSimulator() {
// Set up the JFrame
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Create a label for displaying the message
messageLabel = new JLabel();
messageLabel.setFont(new Font("Arial", Font.PLAIN, 20));
add(messageLabel);
// Create the radio buttons for the traffic lights
JRadioButton redButton = new JRadioButton("Red");
JRadioButton yellowButton = new JRadioButton("Yellow");
JRadioButton greenButton = new JRadioButton("Green");
// Group the radio buttons so only one can be selected at a time
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(redButton);
buttonGroup.add(yellowButton);
buttonGroup.add(greenButton);
// Add the radio buttons to the frame
add(redButton);
add(yellowButton);
add(greenButton);
// Add action listeners to the buttons to change the message based on selection
redButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
messageLabel.setText("Stop");
DEPARTMENT OF COMPUTER SCIENCE
messageLabel.setForeground(Color.RED);
}
});
yellowButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
messageLabel.setText("Ready");
messageLabel.setForeground(Color.YELLOW);
}
});
greenButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
messageLabel.setText("Go");
messageLabel.setForeground(Color.GREEN);
}
});
// Set the initial state
messageLabel.setText(""); // No message initially
messageLabel.setForeground(Color.BLACK); // Default color
// Make the frame visible
setVisible(true);
}
public static void main(String[] args) {
// Create the window and show the traffic light simulator
new TrafficLightSimulator();
}
}
DEPARTMENT OF COMPUTER SCIENCE
OUTPUT
DEPARTMENT OF COMPUTER SCIENCE