Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Java Programs

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Java Programs

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

1.

Java program to print the prime numbers up to a given number N:

import java.util.Scanner;

public class PrimeNumbers {

// Function to check if a number is prime


public static boolean isPrime(int num) {
if (num <= 1) {
return false; // Numbers less than or equal to 1 are not prime
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false; // If divisible by any number, it's not prime
}
}
return true;
}

// Main function
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input: Limit up to which prime numbers need to be printed


System.out.print("Enter a number N to print all prime numbers up to N:
");
int N = scanner.nextInt();

System.out.println("Prime numbers up to " + N + " are:");

// Loop through numbers from 2 to N and print the prime numbers


for (int i = 2; i <= N; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}

scanner.close();
}
}

Explanation:

1. isPrime(int num): This method checks if a given number num is prime. It returns false
if the number is less than or equal to 1 or divisible by any number other than 1 and itself.
Otherwise, it returns true.
2. Input: The program asks the user to input a number N, and it will print all prime numbers
up to N.
3. Loop: The program iterates over all numbers from 2 to N and checks if each number is
prime using the isPrime() method.
4. Output: It prints the prime numbers found within the range.
Example:

If the user inputs:

Enter a number N to print all prime numbers up to N: 20

The output will be:

Prime numbers up to 20 are:


2 3 5 7 11 13 17 19

2. Java program to multiply two matrices:


import java.util.Scanner;

public class MatrixMultiplication {

// Function to multiply two matrices


public static int[][] multiplyMatrices(int[][] matrix1, int[][] matrix2) {
int rowsMatrix1 = matrix1.length;
int colsMatrix1 = matrix1[0].length;
int rowsMatrix2 = matrix2.length;
int colsMatrix2 = matrix2[0].length;

// Check if multiplication is possible


if (colsMatrix1 != rowsMatrix2) {
System.out.println("Matrix multiplication is not possible.");
return null;
}

// Initialize the result matrix


int[][] result = new int[rowsMatrix1][colsMatrix2];

// Multiply the matrices


for (int i = 0; i < rowsMatrix1; i++) {
for (int j = 0; j < colsMatrix2; j++) {
for (int k = 0; k < colsMatrix1; k++) {
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
return result;
}

// Function to print a matrix


public static void printMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}

// Main function
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

// Input for Matrix 1


System.out.print("Enter the number of rows for Matrix 1: ");
int rows1 = scanner.nextInt();
System.out.print("Enter the number of columns for Matrix 1: ");
int cols1 = scanner.nextInt();
int[][] matrix1 = new int[rows1][cols1];
System.out.println("Enter the elements of Matrix 1:");
for (int i = 0; i < rows1; i++) {
for (int j = 0; j < cols1; j++) {
matrix1[i][j] = scanner.nextInt();
}
}

// Input for Matrix 2


System.out.print("Enter the number of rows for Matrix 2: ");
int rows2 = scanner.nextInt();
System.out.print("Enter the number of columns for Matrix 2: ");
int cols2 = scanner.nextInt();
int[][] matrix2 = new int[rows2][cols2];
System.out.println("Enter the elements of Matrix 2:");
for (int i = 0; i < rows2; i++) {
for (int j = 0; j < cols2; j++) {
matrix2[i][j] = scanner.nextInt();
}
}

// Perform matrix multiplication


int[][] result = multiplyMatrices(matrix1, matrix2);

// Output the result matrix


if (result != null) {
System.out.println("Result of Matrix Multiplication:");
printMatrix(result);
}

scanner.close();
}
}

Explanation:

1. Matrix Multiplication Logic:


o The method multiplyMatrices() takes two 2D arrays (matrix1 and matrix2)
as input.
o It checks if the multiplication is possible by ensuring the number of columns in
the first matrix is equal to the number of rows in the second matrix.
o The multiplication is done using three nested loops:
 The outer loop runs over the rows of the first matrix.
 The middle loop runs over the columns of the second matrix.
 The innermost loop computes the dot product of a row from the first
matrix and a column from the second matrix to get the corresponding
value for the result matrix.
2. Input:
oThe program prompts the user to input the dimensions (rows and columns) of
both matrices.
o It then takes the elements of both matrices from the user.
3. Output:
o The program prints the resulting matrix after the multiplication, or displays a
message if matrix multiplication is not possible.

Example:

If the user enters the following input:

Enter the number of rows for Matrix 1: 2


Enter the number of columns for Matrix 1: 3
Enter the elements of Matrix 1:
1 2 3
4 5 6

Enter the number of rows for Matrix 2: 3


Enter the number of columns for Matrix 2: 2
Enter the elements of Matrix 2:
7 8
9 10
11 12

The program will output:

Result of Matrix Multiplication:


58 64
139 154
3. Java program that counts the number of characters, words, and lines in a
given text:
import java.util.Scanner;

public class TextStatistics {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Prompt user to enter text


System.out.println("Enter the text (type 'exit' to stop input and
calculate statistics):");

StringBuilder text = new StringBuilder();


String line;

// Reading lines until user enters 'exit'


while (true) {
line = scanner.nextLine();
if (line.equalsIgnoreCase("exit")) {
break;
}
text.append(line).append("\n");
}

// Getting the entire text


String inputText = text.toString();

// Calculate number of characters, words, and lines


int charCount = inputText.length();
int wordCount = inputText.split("\\s+").length; // Split by whitespace
int lineCount = inputText.split("\n").length; // Split by newline

// Display the results


System.out.println("Number of characters: " + charCount);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of lines: " + lineCount);

scanner.close();
}
}

Explanation:

1. Input: The program allows the user to enter multiple lines of text. The user types "exit"
when they are done, and this input is terminated.
2. StringBuilder: The text is accumulated in a StringBuilder object so that multiple lines
can be stored efficiently.
3. Count Characters: The number of characters is calculated by finding the length of the
entire text (inputText.length()).
4. Count Words: The number of words is found by splitting the text by whitespace
(split("\\s+")). This ensures that any number of spaces between words is handled
correctly.
5. Count Lines: The number of lines is calculated by splitting the text by newline
(split("\n")).
6. Display: The program prints the count of characters, words, and lines.

Example:

If the user enters the following:

Enter the text (type 'exit' to stop input and calculate statistics):
Hello world
This is a Java program
To count characters, words, and lines
exit

The output will be:

Number of characters: 75
Number of words: 13
Number of lines: 4

Explanation of the output:

 Characters: There are 75 characters in the input (including spaces and newline
characters).
 Words: There are 13 words in the input.
 Lines: There are 4 lines in the input (including the exit line, but exit is not counted as
text).
4. Java program that generates a random number between two specified
numbers:
import java.util.Random;
import java.util.Scanner;

public class RandomNumberBetween {

public static void main(String[] args) {


// Create a Scanner object to read user input
Scanner scanner = new Scanner(System.in);

// Prompt user to input the lower and upper bounds


System.out.print("Enter the lower bound: ");
int lowerBound = scanner.nextInt();

System.out.print("Enter the upper bound: ");


int upperBound = scanner.nextInt();

// Check if lowerBound is less than upperBound


if (lowerBound >= upperBound) {
System.out.println("The lower bound should be less than the upper
bound.");
} else {
// Create a Random object to generate random numbers
Random random = new Random();

// Generate a random number between lowerBound (inclusive) and


upperBound (exclusive)
int randomNumber = random.nextInt(upperBound - lowerBound) +
lowerBound;

// Display the random number


System.out.println("Random number between " + lowerBound + " and "
+ upperBound + ": " + randomNumber);
}

// Close the scanner


scanner.close();
}
}

Explanation:

1. Input: The program first prompts the user to input the lower and upper bounds for
generating the random number.
2. Validation: It checks if the lower bound is less than the upper bound. If not, it displays
an error message.
3. Random Generation:
o The Random class is used to generate the random number.
o The method random.nextInt(upperBound - lowerBound) generates a random
number in the range [0, upperBound - lowerBound). By adding the
lowerBound, we shift the range to [lowerBound, upperBound).
4. Output: It prints the random number generated within the specified bounds.

Example:

If the user inputs:

Enter the lower bound: 10


Enter the upper bound: 20

The output will be:

Random number between 10 and 20: 14


5. Java program that demonstrates:

1. Concatenation of a string using a character array.


2. Finding a character in a string.
3. Concatenation of two strings.

import java.util.Scanner;

public class StringOperations {

// Method for concatenating a string using a character array


public static String concatenateUsingCharArray(String str1, String str2) {
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();

// Create a character array for the result


char[] result = new char[charArray1.length + charArray2.length];

// Copy the characters from str1


for (int i = 0; i < charArray1.length; i++) {
result[i] = charArray1[i];
}

// Copy the characters from str2


for (int i = 0; i < charArray2.length; i++) {
result[charArray1.length + i] = charArray2[i];
}

return new String(result);


}

// Method to find a character in a string


public static int findCharacterInString(String str, char character) {
return str.indexOf(character); // Returns the index of the character
or -1 if not found
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input: Two strings


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

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

// Input for character search


System.out.print("Enter a character to find in the first string: ");
char characterToFind = scanner.next().charAt(0);

// Concatenate using character array


String concatenatedString = concatenateUsingCharArray(str1, str2);
System.out.println("Concatenated string using character array: " +
concatenatedString);
// Find the character in the string
int index = findCharacterInString(str1, characterToFind);
if (index != -1) {
System.out.println("Character '" + characterToFind + "' found at
index: " + index);
} else {
System.out.println("Character '" + characterToFind + "' not found
in the string.");
}

// Concatenate two strings using '+' operator


String concatenatedUsingPlus = str1 + str2;
System.out.println("Concatenated string using '+' operator: " +
concatenatedUsingPlus);

scanner.close();
}
}

Explanation:

1. Concatenation using a character array:


o The concatenateUsingCharArray method takes two strings, converts them to
character arrays, and creates a new array to store the concatenated result. It then
combines the characters from both arrays into the result array.
o The new String(result) converts the character array back into a string.
2. Finding a character in a string:
o The findCharacterInString method uses the indexOf method to find the
position of a specified character in the string. If the character is found, it returns
the index of the first occurrence, otherwise, it returns -1.
3. Concatenation of two strings:
o Concatenating two strings is demonstrated using the + operator.

Example:

If the user enters:

Enter the first string: Hello


Enter the second string: World
Enter a character to find in the first string: e

The output will be:

Concatenated string using character array: HelloWorld


Character 'e' found at index: 1
Concatenated string using '+' operator: HelloWorld
6. Java program that demonstrates the following operations using the String
class:

1. String concatenation using the concat() method.


2. Search for a substring using the contains() and indexOf() methods.
3. Extract a substring using the substring() method.

import java.util.Scanner;

public class StringOperations {

// Method to concatenate strings using the concat() method


public static String concatenateStrings(String str1, String str2) {
return str1.concat(str2);
}

// Method to check if a substring exists in a string


public static boolean containsSubstring(String str, String substring) {
return str.contains(substring); // Returns true if the substring
exists in the string
}

// Method to find the index of the first occurrence of a substring


public static int indexOfSubstring(String str, String substring) {
return str.indexOf(substring); // Returns the index of the first
occurrence or -1 if not found
}

// Method to extract a substring from a given string


public static String extractSubstring(String str, int start, int end) {
return str.substring(start, end); // Extracts substring from start
index to end index (exclusive)
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input: Two strings for concatenation and substring operations


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

System.out.print("Enter the second string: ");


String str2 = scanner.nextLine();

// Input for substring search


System.out.print("Enter a substring to search in the first string: ");
String substringToSearch = scanner.nextLine();

// Input for substring extraction


System.out.print("Enter the start index for extracting a substring:
");
int start = scanner.nextInt();

System.out.print("Enter the end index for extracting a substring: ");


int end = scanner.nextInt();
// Concatenate using the concat() method
String concatenatedString = concatenateStrings(str1, str2);
System.out.println("Concatenated string using concat(): " +
concatenatedString);

// Check if the substring is present


if (containsSubstring(str1, substringToSearch)) {
System.out.println("The substring '" + substringToSearch + "'
exists in the first string.");
} else {
System.out.println("The substring '" + substringToSearch + "' does
not exist in the first string.");
}

// Find the index of the substring


int index = indexOfSubstring(str1, substringToSearch);
if (index != -1) {
System.out.println("The substring '" + substringToSearch + "' is
found at index: " + index);
} else {
System.out.println("The substring '" + substringToSearch + "' was
not found.");
}

// Extract a substring
if (start >= 0 && end <= str1.length() && start < end) {
String extractedSubstring = extractSubstring(str1, start, end);
System.out.println("Extracted substring: " + extractedSubstring);
} else {
System.out.println("Invalid start or end index for substring
extraction.");
}

scanner.close();
}
}

Explanation:

1. String Concatenation (concat()):


o The method concatenateStrings() uses the concat() method of the String
class to join two strings together. concat() is used to append one string to the
other.
2. Search for a Substring (contains() and indexOf()):
o The method containsSubstring() checks if the first string contains the
specified substring using the contains() method.
o The method indexOfSubstring() finds the index of the first occurrence of the
substring in the string using the indexOf() method. If the substring is found, it
returns the index; otherwise, it returns -1.
3. Extract a Substring (substring()):
o The method extractSubstring() extracts a part of the string using the
substring(start, end) method, where start is inclusive and end is exclusive.
Example:

If the user enters:

Enter the first string: Hello, how are you?


Enter the second string: I am fine.
Enter a substring to search in the first string: how
Enter the start index for extracting a substring: 7
Enter the end index for extracting a substring: 10

The output will be:

Concatenated string using concat(): Hello, how are you?I am fine.


The substring 'how' exists in the first string.
The substring 'how' is found at index: 7
Extracted substring: how

7. StringBuffer class in Java is a mutable sequence of characters. It allows


for various string manipulations like appending, inserting, reversing,
and deleting characters. In your case, we will use the StringBuffer class
to:

1. Find the length of a string.


2. Reverse a string.
3. Delete a substring from a given string.

Java Program Using StringBuffer:


public class StringBufferOperations {

public static void main(String[] args) {


// Initialize a StringBuffer with an example string
StringBuffer strBuffer = new StringBuffer("Hello, this is a test
string!");

// Display the original string


System.out.println("Original String: " + strBuffer);

// 1. Find the length of the string


System.out.println("Length of the string: " + strBuffer.length());

// 2. Reverse the string


StringBuffer reversedStr = strBuffer.reverse();
System.out.println("Reversed String: " + reversedStr);
// 3. Delete a substring from the string (e.g., deleting "test " from
the original string)
// First, restore the string to the original state before reversing
strBuffer = new StringBuffer("Hello, this is a test string!");
// Delete substring starting from index 18 and of length 5 (substring
"test ")
strBuffer.delete(18, 23);
System.out.println("After Deleting Substring: " + strBuffer);
}
}

Explanation of the Operations:

1. Length of the String:


o The length() method is used to get the number of characters in the
StringBuffer.
o Example:

strBuffer.length(); // Returns the length of the string

2. Reverse the String:


o The reverse() method is used to reverse the string. Note that this method
modifies the StringBuffer object in place and returns the reversed string.
o Example:

strBuffer.reverse(); // Reverses the string in the buffer

3. Delete a Substring:
o The delete(int start, int end) method is used to remove a substring from
the StringBuffer.
o The start index is inclusive, and the end index is exclusive. For example,
delete(18, 23) will remove the substring from index 18 to 22 (inclusive).
o Example:

strBuffer.delete(18, 23); // Deletes the substring from index 18


to 22

Example Output:
plaintext
Copy code
Original String: Hello, this is a test string!
Length of the string: 30
Reversed String: !gnirts tset a si siht ,olleH
After Deleting Substring: Hello, this is a string!

Key Methods Used:

 length(): Returns the length of the StringBuffer.


 reverse(): Reverses the string in the StringBuffer and returns the same
StringBuffer object.
 delete(int start, int end): Deletes a substring from the StringBuffer starting
from start (inclusive) to end (exclusive).

Running the Program:

1. Save the code in a file named StringBufferOperations.java.


2. Compile the program:

javac StringBufferOperations.java

3. Run the program:

java StringBufferOperations

8. Java program that implements a multi-threaded application with the


described functionality. The program consists of three threads:

1. First thread: Generates a random integer every second.


2. Second thread: Computes and prints the square of the number if it is even.
3. Third thread: Computes and prints the cube of the number if it is odd.

Java Code:
import java.util.Random;

public class MultiThreadedRandomProcessing {

// Shared variable to store the generated random number


static int randomNumber = 0;

// Main thread that generates a random number every second


static class RandomNumberGenerator extends Thread {
public void run() {
Random random = new Random();
while (true) {
// Generate a random integer between 1 and 100
randomNumber = random.nextInt(100) + 1;
System.out.println("Generated number: " + randomNumber);
try {
// Sleep for 1 second before generating the next number
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("RandomNumberGenerator interrupted");
}
}
}
}

// Second thread that calculates and prints the square if the number is
even
static class SquareCalculator extends Thread {
public void run() {
while (true) {
// Check if the number is even
if (randomNumber % 2 == 0) {
int square = randomNumber * randomNumber;
System.out.println("Square of " + randomNumber + ": " +
square);
}
try {
// Sleep for a short time to avoid busy-waiting
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("SquareCalculator interrupted");
}
}
}
}

// Third thread that calculates and prints the cube if the number is odd
static class CubeCalculator extends Thread {
public void run() {
while (true) {
// Check if the number is odd
if (randomNumber % 2 != 0) {
int cube = randomNumber * randomNumber * randomNumber;
System.out.println("Cube of " + randomNumber + ": " +
cube);
}
try {
// Sleep for a short time to avoid busy-waiting
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("CubeCalculator interrupted");
}
}
}
}

public static void main(String[] args) {


// Create and start the threads
RandomNumberGenerator randomThread = new RandomNumberGenerator();
SquareCalculator squareThread = new SquareCalculator();
CubeCalculator cubeThread = new CubeCalculator();

randomThread.start();
squareThread.start();
cubeThread.start();
}
}

Explanation:

1. RandomNumberGenerator Thread:
o This thread generates a random number between 1 and 100 every second
(Thread.sleep(1000)).
o The number is stored in the shared variable randomNumber.
2. SquareCalculator Thread:
o This thread continuously checks if the randomNumber is even. If it is, it computes
the square of the number and prints it.
o It sleeps for 500 milliseconds to avoid busy-waiting and to allow other threads to
run.
3. CubeCalculator Thread:
o This thread continuously checks if the randomNumber is odd. If it is, it computes
the cube of the number and prints it.
o It also sleeps for 500 milliseconds to avoid busy-waiting.

Key Points:

 The program uses a shared variable randomNumber to communicate the random number
generated by the first thread with the second and third threads.
 All threads run continuously in an infinite loop. They perform their respective tasks
(generating a random number, computing square or cube) and then sleep for a short
period to avoid overloading the CPU.
 Threads are synchronized with sleep intervals to allow them to run efficiently and not
consume unnecessary CPU time.

Example Output:
Generated number: 75
Cube of 75: 421875
Generated number: 32
Square of 32: 1024
Generated number: 11
Cube of 11: 1331
Generated number: 48
Square of 48: 2304
9. Java program that demonstrates how to use threads asynchronously to
print the numbers from 1 to 10 using Thread1 and from 90 to 100 using
Thread2. The program uses the same method in both threads to print
numbers, but each thread prints a different range of numbers:

Java Code:
public class AsynchronousThreadExample {

// Shared method to print numbers


public static synchronized void printNumbers(int start, int end) {
for (int i = start; i <= end; i++) {
System.out.println(i);
try {
// Sleep for 100 milliseconds to simulate some delay
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("Thread interrupted");
}
}
}

// Thread1: prints numbers from 1 to 10


static class Thread1 extends Thread {
public void run() {
printNumbers(1, 10);
}
}

// Thread2: prints numbers from 90 to 100


static class Thread2 extends Thread {
public void run() {
printNumbers(90, 100);
}
}

public static void main(String[] args) {


// Create instances of Thread1 and Thread2
Thread1 thread1 = new Thread1();
Thread2 thread2 = new Thread2();

// Start both threads


thread1.start();
thread2.start();
}
}

Explanation:

1. printNumbers Method:
o This method takes two arguments, start and end, and prints numbers from
start to end.
o It uses Thread.sleep(100) to simulate a small delay (100 milliseconds) between
printing each number. This helps illustrate asynchronous behavior.
2. Thread1 and Thread2 Classes:
o Thread1 calls the printNumbers method to print numbers from 1 to 10.
o Thread2 calls the printNumbers method to print numbers from 90 to 100.
3. main Method:
o Instances of Thread1 and Thread2 are created and started asynchronously by
calling their start() method.
4. Synchronization:
o The printNumbers method is marked as synchronized to ensure that even
though both threads use the same method, they do not print numbers
simultaneously in an interleaved way. This helps prevent thread interference or
inconsistent output when multiple threads try to access the same method at the
same time.

Output Example:
Copy code
1
2
3
4
5
6
7
8
9
10
90
91
92
93
94
95
96
97
98
99
100
10.Java program that demonstrates the use of the following exceptions:

1. Arithmetic Exception - Occurs when an illegal arithmetic operation, such as division by


zero, is performed.
2. Number Format Exception - Occurs when an attempt is made to convert a string to a
number in an invalid format.
3. Array Index Out of Bound Exception - Occurs when an attempt is made to access an
array with an invalid index.
4. Negative Array Size Exception - Occurs when trying to create an array with a negative
size.

Java Code:
public class ExceptionDemo {

public static void main(String[] args) {

// a. Arithmetic Exception (e.g., division by zero)


try {
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Exception: " + e.getMessage());
}

// b. Number Format Exception (e.g., trying to convert a non-numeric


string to an integer)
try {
int number = Integer.parseInt("abc"); // This will throw
NumberFormatException
} catch (NumberFormatException e) {
System.out.println("Number Format Exception: " + e.getMessage());
}

// c. Array Index Out of Bound Exception (e.g., accessing an invalid


index)
try {
int[] arr = new int[5];
arr[10] = 100; // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Out of Bound Exception: " +
e.getMessage());
}

// d. Negative Array Size Exception (e.g., creating an array with


negative size)
try {
int[] arr = new int[-5]; // This will throw
NegativeArraySizeException
} catch (NegativeArraySizeException e) {
System.out.println("Negative Array Size Exception: " +
e.getMessage());
}
}
}

Explanation of Exceptions:

1. ArithmeticException:
o Occurs when an illegal arithmetic operation is performed. In the example,
division by zero (10 / 0) throws an ArithmeticException.
o The message "divide by zero" is captured by the exception handler.
2. NumberFormatException:
o Occurs when trying to convert a string to a number, but the string does not have a
valid format. In this case, we try to parse "abc" as an integer, which is invalid.
o The parseInt("abc") will throw a NumberFormatException.
3. ArrayIndexOutOfBoundsException:
o Occurs when trying to access an array element using an invalid index. In this case,
we try to assign a value to arr[10], but the array only has indices 0 to 4, so an
ArrayIndexOutOfBoundsException is thrown.
4. NegativeArraySizeException:
o Occurs when trying to create an array with a negative size. The line new int[-5]
tries to create an array with a negative size, which throws a
NegativeArraySizeException.

Example Output:
Arithmetic Exception: / by zero
Number Format Exception: For input string: "abc"
Array Index Out of Bound Exception: Index 10 out of bounds for length 5
Negative Array Size Exception: Size of array is negative
11. Java program that reads a file name from the user and displays the
following information about the file:

1. Whether the file exists.


2. Whether the file is readable.
3. Whether the file is writable.
4. The type of the file (whether it's a directory or a regular file).
5. The length of the file in bytes.

Java Code:
import java.io.File;
import java.util.Scanner;

public class FileInformation {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Ask the user for the file name


System.out.print("Enter the file name (with path if necessary): ");
String fileName = scanner.nextLine();

// Create a File object


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 it's a directory or a regular file


if (file.isDirectory()) {
System.out.println("File is a directory.");
} else if (file.isFile()) {
System.out.println("File is a regular file.");
}
// Get the file size in bytes
System.out.println("File length: " + file.length() + " bytes");

} else {
System.out.println("File does not exist.");
}

// Close the scanner


scanner.close();
}
}

Explanation:

1. File object: A File object is created using the file name provided by the user. The File
class is part of java.io package, and it provides various methods to get information
about the file.
2. Checking file existence:
o file.exists() returns true if the file exists, otherwise false.

3. Checking readability and writability:


o file.canRead() returns true if the file is readable.
o file.canWrite() returns true if the file is writable.

4. Checking file type:


o file.isDirectory() checks if the file is a directory.
o file.isFile() checks if the file is a regular file (not a directory).

5. File size:
o file.length() returns the size of the file in bytes.

Example Output:

Case 1: File exists and is a regular file


Enter the file name (with path if necessary): example.txt
File exists: Yes
File is readable: Yes
File is writable: Yes
File is a regular file.
File length: 1024 bytes
Case 2: File does not exist
Enter the file name (with path if necessary): non_existent_file.txt
File does not exist.
12. Java program that demonstrates this functionality using Java Swing:

Java Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TextEditorApp extends JFrame {

// Components
private JTextArea textArea;
private JComboBox<String> fontSizeComboBox;
private JCheckBox boldCheckBox, italicCheckBox;

public TextEditorApp() {
// Set frame title and layout
setTitle("Text Editor with Font and Style Options");
setLayout(new BorderLayout());

// Create JTextArea 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 size, bold, italic)


JPanel controlPanel = new JPanel();

// Font size combo box


String[] fontSizes = {"10", "12", "14", "16", "18", "20", "22", "24"};
fontSizeComboBox = new JComboBox<>(fontSizes);
fontSizeComboBox.setSelectedIndex(2); // Default font size is 14
fontSizeComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateTextStyle();
}
});
controlPanel.add(new JLabel("Font Size:"));
controlPanel.add(fontSizeComboBox);

// Bold checkbox
boldCheckBox = new JCheckBox("Bold");
boldCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateTextStyle();
}
});
controlPanel.add(boldCheckBox);
// Italic checkbox
italicCheckBox = new JCheckBox("Italic");
italicCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateTextStyle();
}
});
controlPanel.add(italicCheckBox);

// Add the control panel at the top of the frame


add(controlPanel, BorderLayout.NORTH);

// Set default window settings


setSize(500, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null); // Center the window on screen
}

// Method to update text style based on user input


private void updateTextStyle() {
// Get the selected font size
int fontSize = Integer.parseInt((String)
fontSizeComboBox.getSelectedItem());

// Get the current font style (Plain by default)


int fontStyle = Font.PLAIN;
if (boldCheckBox.isSelected()) {
fontStyle |= Font.BOLD; // Add bold style if checked
}
if (italicCheckBox.isSelected()) {
fontStyle |= Font.ITALIC; // Add italic style if checked
}

// Update the font of the JTextArea


textArea.setFont(new Font("Arial", fontStyle, fontSize));
}

public static void main(String[] args) {


// Run the application
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new TextEditorApp().setVisible(true);
}
});
}
}

Explanation of the Code:

1. JTextArea: This is where the user can enter the text. It is wrapped inside a JScrollPane
to make it scrollable when the text becomes long.
2. JComboBox: This dropdown menu allows the user to select the font size. We use an
array of font sizes (fontSizes), and the selected item in the JComboBox is used to update
the font size of the text in the JTextArea.
3. JCheckBox: There are two checkboxes:
o One for enabling/disabling bold.
o One for enabling/disabling italic.

These checkboxes allow the user to toggle the respective styles on or off.

4. Font update logic: The updateTextStyle method is called whenever the user interacts
with the controls. It checks the current settings of the font size, bold, and italic options
and updates the font style of the text area accordingly.
5. Swing GUI components: The frame (JFrame) contains a central text area for input and a
control panel at the top for selecting the font size and toggling bold/italic options.
6. Main method: The application is run inside the main method, and the GUI is made
visible by calling setVisible(true) on the frame.

How the Program Works:

 When the program starts, a text area appears with a default font size of 14 and no bold or
italic styles.
 The user can change the font size by selecting a different option in the combo box.
 The user can toggle bold or italic by checking or unchecking the respective checkboxes.
 The text area updates in real-time as the user changes any of the options.

Example Output:

Upon running the program, you will see a window with:

 A large text area for inputting text.


 A control panel above the text area with:
o A dropdown to select the font size.
o Two checkboxes for bold and italic styles.

After typing text, the user can change the font size, make the text bold or italic, and the changes
will reflect in the text area immediately.

Key Swing Components Used:

 JTextArea: A multi-line area to display/edit text.


 JComboBox: A dropdown for selecting font sizes.
 JCheckBox: For selecting bold or italic options.
 JPanel: A container for organizing controls.
 JScrollPane: For adding scroll functionality to the text area.
12. To create a Java program that allows the user to accept a text and change
its size and font, including bold and italic options, we can use Swing for
creating a GUI with controls. This will include:

1. A JTextArea to accept and display the text.


2. A JComboBox to select the font family.
3. A JComboBox to select the font size.
4. Checkboxes to toggle Bold and Italic options.
5. A JButton to apply the selected changes to the text.

Java Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class FontChangerApp extends JFrame {

// Components declaration
private JTextArea textArea;
private JComboBox<String> fontComboBox, sizeComboBox;
private JCheckBox boldCheckBox, italicCheckBox;
private JButton applyButton;

public FontChangerApp() {
// Set up the JFrame properties
setTitle("Font and Style Changer");
setSize(600, 400);
setLocationRelativeTo(null); // Center the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

// Create the text area for user input


textArea = new JTextArea("Enter text here...");
textArea.setFont(new Font("Arial", Font.PLAIN, 14));
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);

// Create the control panel for font selection


JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());

// Font family combo box


String[] fonts = {"Arial", "Courier New", "Verdana", "Times New
Roman"};
fontComboBox = new JComboBox<>(fonts);
fontComboBox.setSelectedItem("Arial");
// Font size combo box
String[] sizes = {"12", "14", "16", "18", "20", "22", "24", "26"};
sizeComboBox = new JComboBox<>(sizes);
sizeComboBox.setSelectedItem("14");

// Bold and Italic checkboxes


boldCheckBox = new JCheckBox("Bold");
italicCheckBox = new JCheckBox("Italic");

// Apply button
applyButton = new JButton("Apply");

// Add components to control panel


controlPanel.add(new JLabel("Font:"));
controlPanel.add(fontComboBox);
controlPanel.add(new JLabel("Size:"));
controlPanel.add(sizeComboBox);
controlPanel.add(boldCheckBox);
controlPanel.add(italicCheckBox);
controlPanel.add(applyButton);

// Add the components to the frame


add(new JScrollPane(textArea), BorderLayout.CENTER);
add(controlPanel, BorderLayout.SOUTH);

// Button listener to apply changes


applyButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selectedFont = (String) fontComboBox.getSelectedItem();
int selectedSize = Integer.parseInt((String)
sizeComboBox.getSelectedItem());
int style = Font.PLAIN;

// Set style based on checkboxes


if (boldCheckBox.isSelected() && italicCheckBox.isSelected())
{
style = Font.BOLD | Font.ITALIC;
} else if (boldCheckBox.isSelected()) {
style = Font.BOLD;
} else if (italicCheckBox.isSelected()) {
style = Font.ITALIC;
}

// Apply the selected font, size, and style to the text area
textArea.setFont(new Font(selectedFont, style, selectedSize));
}
});
}

public static void main(String[] args) {


// Create and display the font changer application
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new FontChangerApp().setVisible(true);
}
});
}
}

Explanation of the Code:

1. Components:
o JTextArea: This area is where the user can type the text. It is initialized with
some default text ("Enter text here...").
o JComboBox<String> (fontComboBox, sizeComboBox): These combo boxes are
used to select the font family and font size.
o JCheckBox (boldCheckBox, italicCheckBox): These checkboxes let the user
toggle the Bold and Italic styles.
o JButton (applyButton): A button to apply the selected font family, size, and style
to the text area.
2. Layout:
o The JFrame uses a BorderLayout. The JTextArea is placed in the center of the
frame, and the control panel (which holds the combo boxes, checkboxes, and the
apply button) is placed at the bottom (south).
3. Font Application:
o When the user clicks the Apply button, an ActionListener is triggered. This
listener fetches the selected font family, size, and style. Based on the selected
options, the style is calculated (Font.BOLD, Font.ITALIC, or both). Then, the font
is applied to the JTextArea by creating a new Font object and calling setFont()
on the JTextArea.
4. Font Style Calculation:
o The program checks whether both Bold and Italic are selected. If both are
selected, the style is set to both Font.BOLD and Font.ITALIC. If only one is
selected, it applies the respective style.

How the Program Works:

1. Text Area: The user can enter any text into the JTextArea. This is the area where the
font and style changes will be applied.
2. Font and Size Selection: The user can select the font family and font size from the
combo boxes.
3. Bold and Italic: The user can toggle Bold and Italic using the checkboxes.
4. Apply Button: Once the user has selected the desired font family, size, and styles, they
can click the Apply button, which will update the text in the JTextArea with the new
font settings.

Example Output:

1. Initially, the JTextArea will display "Enter text here...".


2. After selecting "Courier New" from the font combo box, "20" from the size combo box,
and checking the Bold checkbox, clicking the Apply button will make the text in the
JTextArea appear in Bold Courier New font with size 20.
3. If the Italic checkbox is also selected, the text will appear in both Bold and Italic.
Running the Program:

1. Save the code as FontChangerApp.java.


2. Compile the program:

javac FontChangerApp.java

3. Run the program:

java FontChangerApp

A window will appear where you can input text and adjust its font, size, and style using the
provided controls.

Key Components:

 JTextArea: For user input.


 JComboBox: For font family and size selection.
 JCheckBox: For bold and italic options.
 JButton: To apply changes to the text.

13. Java program, we will handle all mouse events (mouse clicked, mouse
pressed, mouse released, mouse entered, and mouse exited) using
MouseAdapter. When a mouse event is triggered, the event's name will be
displayed at the center of the window.

Steps:

1. MouseAdapter: We will extend the MouseAdapter class because it provides default


implementations for all mouse event methods, which we can override as needed. This
allows us to handle specific mouse events without implementing unnecessary methods.
2. MouseEvent: Each mouse event will provide information about the specific event
triggered, and we will use that information to display the event name at the center of the
window.
3. Graphics: We will use Graphics to draw the event name on the window.

Java Code:
import java.awt.*;
import java.awt.event.*;

public class MouseEventDemo extends Frame {


private String eventName = ""; // Variable to hold the current event name

// Constructor to set up the Frame


public MouseEventDemo() {
setTitle("Mouse Event Handler");
setSize(400, 400);
setLocationRelativeTo(null); // Center the window
setVisible(true);

// Add a MouseListener using MouseAdapter


addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
eventName = "Mouse Clicked";
repaint();
}

public void mousePressed(MouseEvent e) {


eventName = "Mouse Pressed";
repaint();
}

public void mouseReleased(MouseEvent e) {


eventName = "Mouse Released";
repaint();
}

public void mouseEntered(MouseEvent e) {


eventName = "Mouse Entered";
repaint();
}

public void mouseExited(MouseEvent e) {


eventName = "Mouse Exited";
repaint();
}
});
}

// Override the paint method to display the event name


public void paint(Graphics g) {
// Get the width and height of the frame
int width = getWidth();
int height = getHeight();

// Set font style and size


g.setFont(new Font("Arial", Font.BOLD, 20));
FontMetrics metrics = g.getFontMetrics();

// Get the width and height of the text to center it


int textWidth = metrics.stringWidth(eventName);
int textHeight = metrics.getHeight();

// Draw the event name at the center of the window


g.setColor(Color.BLACK);
g.drawString(eventName, (width - textWidth) / 2, (height + textHeight)
/ 2);
}
// Main method to run the program
public static void main(String[] args) {
// Create an instance of the MouseEventDemo frame
new MouseEventDemo();
}
}

Explanation of the Program:

1. MouseEventDemo Class:
o This class extends Frame, a top-level window provided by AWT.
o We have a String eventName to store the name of the event that is triggered
(e.g., "Mouse Clicked").
o We use the addMouseListener method to listen for mouse events. The
MouseAdapter class is used so we can override only the methods we need.
2. MouseAdapter:
o The mouseClicked(), mousePressed(), mouseReleased(), mouseEntered(),
and mouseExited() methods are overridden to capture each specific mouse
event.
o Whenever an event occurs, the eventName variable is updated with the
corresponding event name, and repaint() is called to trigger a redraw of the
window.
3. Painting the Event Name:
o The paint() method is overridden to display the eventName at the center of the
window.
o We calculate the width and height of the event name text using FontMetrics to
ensure it's centered both horizontally and vertically.
4. Frame Setup:
o The frame is created with the title "Mouse Event Handler" and is set to be visible
at the center of the screen with a size of 400x400 pixels.

How the Program Works:

 When you run the program, a window will appear.


 When you click, press, release, enter, or exit the mouse over the window, the
corresponding mouse event name will be displayed at the center of the window.
 The program listens to all five mouse events and updates the display accordingly.

Example Output:

1. Clicking the mouse will display "Mouse Clicked" at the center of the window.
2. Pressing the mouse will display "Mouse Pressed".
3. Releasing the mouse will display "Mouse Released".
4. Entering the window with the mouse will display "Mouse Entered".
5. Exiting the window with the mouse will display "Mouse Exited".
14. Java program that implements a simple calculator with a graphical user
interface (GUI) using the GridLayout to arrange buttons for digits and
arithmetic operations. The calculator supports basic operations such as
addition, subtraction, multiplication, division, and modulus, and handles
division by zero exceptions.

Java Program for a Simple Calculator:


import java.awt.*;
import java.awt.event.*;

public class SimpleCalculator extends Frame {

// Declare components
private TextField display;
private String currentInput = ""; // To hold the current input
private double result = 0; // To hold the result of operations
private String operator = ""; // To hold the operator (+, -, *, /, %)

public SimpleCalculator() {
// Set the frame layout and title
setTitle("Simple Calculator");
setSize(400, 500);
setLocationRelativeTo(null); // Center the window
setLayout(new BorderLayout());

// Display TextField at the top of the window


display = new TextField();
display.setEditable(false);
display.setFont(new Font("Arial", Font.PLAIN, 24));
add(display, BorderLayout.NORTH);

// Create a panel for the buttons (digits and operators)


Panel panel = new Panel();
panel.setLayout(new GridLayout(4, 4, 10, 10));

// Add digit buttons


String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+",
};

for (String text : buttons) {


Button button = new Button(text);
button.setFont(new Font("Arial", Font.PLAIN, 20));
button.addActionListener(new ButtonClickListener());
panel.add(button);
}

add(panel, BorderLayout.CENTER);

// Close the window when the close button is clicked


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}

// Button click event handler


private class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String buttonText = e.getActionCommand();

// If the "=" button is clicked, evaluate the expression


if (buttonText.equals("=")) {
try {
result = evaluateExpression(currentInput);
display.setText(String.valueOf(result));
currentInput = String.valueOf(result); // Store the result
for further calculation
operator = ""; // Clear operator
} catch (ArithmeticException ex) {
display.setText("Error");
currentInput = "";
}
}
// If the operator button is clicked, store the current input and
operator
else if (buttonText.equals("+") || buttonText.equals("-") ||
buttonText.equals("*") || buttonText.equals("/") || buttonText.equals("%")) {
operator = buttonText;
result = Double.parseDouble(currentInput);
currentInput = "";
}
// If the button is a digit or decimal point, append it to the
current input
else {
currentInput += buttonText;
display.setText(currentInput);
}
}
}

// Method to evaluate the expression


private double evaluateExpression(String expression) throws
ArithmeticException {
double result = 0;
String[] tokens;

if (expression.contains("+")) {
tokens = expression.split("\\+");
result = Double.parseDouble(tokens[0]) +
Double.parseDouble(tokens[1]);
} else if (expression.contains("-")) {
tokens = expression.split("-");
result = Double.parseDouble(tokens[0]) -
Double.parseDouble(tokens[1]);
} else if (expression.contains("*")) {
tokens = expression.split("\\*");
result = Double.parseDouble(tokens[0]) *
Double.parseDouble(tokens[1]);
} else if (expression.contains("/")) {
tokens = expression.split("/");
if (Double.parseDouble(tokens[1]) == 0) {
throw new ArithmeticException("Divide by zero");
}
result = Double.parseDouble(tokens[0]) /
Double.parseDouble(tokens[1]);
} else if (expression.contains("%")) {
tokens = expression.split("%");
result = Double.parseDouble(tokens[0]) %
Double.parseDouble(tokens[1]);
}
return result;
}

// Main method to run the application


public static void main(String[] args) {
// Launch the calculator application
new SimpleCalculator().setVisible(true);
}
}

Explanation of the Code:

1. Frame Layout:
o We use a BorderLayout for the main frame with the TextField at the top for
displaying the result.
o The buttons for digits and operators are arranged using a GridLayout in a 4x4
grid. This includes digits 0-9, arithmetic operators (+, -, *, /, %), and an "="
button for evaluation.
2. TextField:
o TextField display is used to show the current expression or result. It is set to
be non-editable (setEditable(false)) so the user can only see the result.
3. Buttons:
o The buttons for digits (0-9) and operators are created dynamically and added to
the panel.
o Each button has an ActionListener attached to handle clicks and update the
currentInput or perform the calculation when "=" is clicked.
4. ButtonClickListener:
o The ButtonClickListener class is responsible for handling button clicks. When
a button is clicked:
 If "=" is clicked, the expression is evaluated using
evaluateExpression().
 If an operator is clicked, it stores the current input and operator.
 Otherwise, it appends the clicked digit or decimal point to the
currentInput.
5. Evaluation Logic:
o The evaluateExpression method evaluates the mathematical expression based
on the operator. It splits the expression by the operator, performs the calculation,
and returns the result.
o The method handles division by zero by throwing an ArithmeticException.
6. Error Handling:
o If the user tries to divide by zero, the program catches the exception and displays
"Error" in the text field.
7. Closing the Frame:
o The window will close when the user clicks the close button by listening to the
WindowAdapter.

Example Usage:

When the program is run, you will see a simple calculator window with buttons for digits,
arithmetic operators, and an "=" button for calculating the result.

 For example:
o Click 5, +, 3, and then = to get the result 8.
o If you click 10, /, 0, and then =, it will display "Error" since dividing by zero is
not allowed.
15. To simulate a traffic light system using Java, we can utilize Swing
components, which are a part of the Java Foundation Classes (JFC). We'll use
a JRadioButton for the three traffic light colors (red, yellow, and green), and
depending on the user's selection, an appropriate message ("stop", "ready",
or "go") will appear above the buttons in the selected color.

Java Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TrafficLightSimulator extends JFrame {

// Declare components
private JRadioButton redButton, yellowButton, greenButton;
private JLabel messageLabel;
private ButtonGroup buttonGroup;

public TrafficLightSimulator() {
// Set up the frame
setTitle("Traffic Light Simulator");
setSize(400, 300);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Initialize components
redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");

// Group the radio buttons so only one can be selected at a time


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

// Initialize the message label (initially empty)


messageLabel = new JLabel("");
messageLabel.setFont(new Font("Arial", Font.BOLD, 20));

// Add action listeners to radio buttons


redButton.addActionListener(new TrafficLightListener());
yellowButton.addActionListener(new TrafficLightListener());
greenButton.addActionListener(new TrafficLightListener());

// Add components to the frame


add(messageLabel);
add(redButton);
add(yellowButton);
add(greenButton);

// Set the frame to be visible


setLocationRelativeTo(null); // Center the window
setVisible(true);
}

// ActionListener class to handle radio button selection


private class TrafficLightListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// Check which radio button is selected
if (redButton.isSelected()) {
messageLabel.setText("Stop");
messageLabel.setForeground(Color.RED);
} else if (yellowButton.isSelected()) {
messageLabel.setText("Ready");
messageLabel.setForeground(Color.YELLOW);
} else if (greenButton.isSelected()) {
messageLabel.setText("Go");
messageLabel.setForeground(Color.GREEN);
}
}
}

public static void main(String[] args) {


// Create the traffic light simulator instance
new TrafficLightSimulator();
}
}

Explanation of the Code:

1. JRadioButton:
o Three radio buttons are created for the red, yellow, and green traffic lights:
redButton, yellowButton, and greenButton.
o JRadioButton is used because it allows only one button to be selected at a time
when grouped together with ButtonGroup.
2. ButtonGroup:
o We group the radio buttons (redButton, yellowButton, and greenButton) using
a ButtonGroup. This ensures that only one radio button can be selected at a time.
3. JLabel:
o messageLabel is a JLabel used to display the traffic light message ("Stop",
"Ready", "Go"). Initially, it displays nothing ("").
o The label's text color is set dynamically based on the selected radio button.
4. ActionListener:
o An ActionListener is added to each radio button. When a radio button is
selected, the appropriate message is displayed in the label with the corresponding
color (red, yellow, or green).
5. FlowLayout:
o A FlowLayout is used to arrange the components in a simple and clean manner.
The message is displayed at the top, followed by the three radio buttons arranged
vertically.
6. Font and Appearance:
o The font of the message label is set to be bold and of size 20 for better visibility.
o The color of the message label changes according to the selected traffic light.
7. Main Method:
o In the main method, we create an instance of the TrafficLightSimulator class,
which sets up the GUI and makes it visible.

How the Program Works:

 Initially, there is no message shown.


 When the user selects one of the radio buttons (Red, Yellow, or Green):
o If the Red button is selected, the label displays "Stop" in red.
o If the Yellow button is selected, the label displays "Ready" in yellow.
o If the Green button is selected, the label displays "Go" in green.
 The layout is simple, and the program uses a FlowLayout to display the components.

Key Components:

 JRadioButton: For creating selectable options (Red, Yellow, Green).


 ButtonGroup: Ensures only one radio button can be selected at a time.
 JLabel: Used for displaying the message above the buttons.
 ActionListener: Handles the event when a radio button is selected.

Example Output:

1. When the Red radio button is selected, the label will show "Stop" in red color.
2. When the Yellow radio button is selected, the label will show "Ready" in yellow color.
3. When the Green radio button is selected, the label will show "Go" in green color.

Running the Program:

 Save the code in a file named TrafficLightSimulator.java.


 Compile and run the program:

javac TrafficLightSimulator.java
java TrafficLightSimulator

You might also like