0% found this document useful (0 votes)
180 views36 pages

Java Programs 2025 Ii BSC CS

The document outlines various Java programming exercises, including prime number generation, matrix multiplication, text analysis, random number generation, string manipulation, string operations, string buffer operations, multi-threading, and exception handling. Each exercise includes an aim, algorithm, program code, and results indicating successful execution. The content is structured for educational purposes in a computer science department.

Uploaded by

kaminiganesan13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
180 views36 pages

Java Programs 2025 Ii BSC CS

The document outlines various Java programming exercises, including prime number generation, matrix multiplication, text analysis, random number generation, string manipulation, string operations, string buffer operations, multi-threading, and exception handling. Each exercise includes an aim, algorithm, program code, and results indicating successful execution. The content is structured for educational purposes in a computer science department.

Uploaded by

kaminiganesan13
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 01

EX NO : 01
PRIME NUMBERS
DATE :

AIM :
To write a Java program that prompts the user for an integer and
then prints out all the prime numbers up to that Integer.

ALGORITHM :
Step 1: Take the input number from the user using a Scanner.
Step 2: Check if the number is less than 2; if true, print "Not Prime".
Step 3: Loop from 2 to the square root of the number.
Step 4: Inside the loop, check if the number is divisible by the current
value.
Step 5: If divisible, print "Not Prime" and stop.
Step 6: If the loop completes without finding divisors, print "Prime".
Step 7: Close the scanner to free resources .

PROGRAM CODE :

import java.util.Scanner;
public class PrimeNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int num = scanner.nextInt();
System.out.println("Prime numbers up to "+num+":");
for (int i = 2; i <= num; i++) {
boolean isPrime = true;
for (int j = 2; j < i; j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(i+" ");
}
}

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 02

}
}

OUTPUT :

RESULT :

Thus the above Program was successfully executed and the output was
verified.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 03
EX NO : 02
MATRIX MULTIPLICATION
DATE :

AIM :

To Write a Java program to multiply two given matrices.

ALGORITHM :
Step 1: Take input for two matrices from the user (dimensions and
elements).
Step 2: Check if the number of columns in Matrix A equals the
number of rows in Matrix B.
Step 3: Create a result matrix of size (rows of Matrix A) x (columns of
Matrix B).
Step 4: Use nested loops to iterate through rows of Matrix A and
columns of Matrix B.
Step 5: Multiply elements of the corresponding row and column, and
sum them up to fill each cell in the result matrix.
Step 6: Print the result matrix.

PROGRAM CODE :

public class MatrixMultiplication {


public static void main(String[] args) {
int[][] matrix1 = { {1, 2}, {3, 4} };
int[][] matrix2 = { {5, 6}, {7, 8} };
int[][] result = new int[2][2];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
result[i][j] = matrix1[i][0] * matrix2[0][j] + matrix1[i][1] *
matrix2[1][j];
}
}
System.out.println("Result:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(result[i][j] + " ");

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 04

}
System.out.println();
}
}
}

OUTPUT :

RESULT:

Thus the above Java program implementing Matrix Multiplication was


executed successfully

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 05
EX NO : 03
TEXT ANALYZER
DATE :

AIM :
To develop a Java program that displays the number of characters,
lines and words in a text.

ALGORITHM :

Step 1: Take input text from the user.


Step 2: Remove unnecessary spaces and standardize the case
(optional).
Step 3: Count the number of characters.
Step 4: Count the number of words (split text by spaces).
Step 5: Count the number of sentences (split by ., !, or ?).
Step 6: Display the analysis results to the user.

PROGRAM CODE :

public class TextAnalyzer


{
public static void main(String[] args)
{
String text = "Hello world\nJava programming is fun\nThis is a
simple program.";
int lineCount = text.split("\n").length;
int wordCount = text.split("\\s+").length;
int characterCount = text.length();
System.out.println("Number of lines: " + lineCount);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of characters: " + characterCount);
}
}

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 06

OUTPUT :

RESULT :

Thus the above Java program implementing a Text Analyzer was


executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 07
EX NO: 04
RANDOM NUMBERS
DATE :

AIM :

To develop a Java program Generate random numbers between


two given limits using Random class and print messages according
to the range of the value generated.

ALGORITHM :

Step 1: Import the java.util.Random or use Math.random().


Step 2: Create a Random object (if using Random).
Step 3: Use the appropriate method to generate random numbers.
Step 4: Print or use the random numbers in your program.

PROGRAM CODE :

import java.util.Random;
public class RandomNumber {
public static void main(String[] args) {
int lowerLimit = 10;
int upperLimit = 50;
Random random = new Random();
int randomNumber = random.nextInt(upperLimit - lowerLimit + 1) +
lowerLimit;
System.out.println("Generated number: " + randomNumber);
if (randomNumber < 20) {
System.out.println("The number is less than 20.");
} else if (randomNumber <= 35) {
System.out.println("The number is between 20 and 35.");
}

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 08

else {
System.out.println("The number is greater than 35.");
}
}
}

OUTPUT :

RESULT:
Thus the above Java program for generate Random numbers was
executed Successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 09
EX NO: 05
STRING MANIPULATION
DATE :

AIM :

To develop a Java program to do String Manipulation using


Character Array and perform the following string operations: String
length,Finding a character at a particular position, Concatenating two
strings.

ALGORITHM :
Step 1: Input the string using Scanner.
Step 2: Concatenate the string with another string.
Step 3: Extract a substring from the string.
Step 4: Find the length of the string.
Step 5: Access a specific character in the string.
Step 6: Replace specific characters or substrings.
Step 7: Split the string into an array of words.

PROGRAM CODE :

public class StringManipulation {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
System.out.println("Length of str1: " + charArray1.length);
System.out.println("Character at position 2 in str1: " +
charArray1[2]);
char[] result = new char[charArray1.length +
charArray2.length];
System.arraycopy(charArray1, 0, result, 0, charArray1.length);
System.arraycopy(charArray2, 0, result, charArray1.length,
charArray2.length);

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 10

System.out.println("Concatenated string: " + new String(result));


}
}

OUTPUT :

RESULT :

Thus the Java programming used to implement String Manipulation


was executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 11
EX NO : 06
STRING OPERATIONS
DATE :

AIM :
To develop a Java program to perform the following string operations
using String class: String Concatenation, Search a substring,To extract
substring from given string.

ALGORITHM :

Step 1: Declare two string variables str1 and str2 and initialize
them with "Hello" and "World" respectively.
Concatenate str1 and str2 with a space (" ") in between.
Step 2 : Declare a string variable searchSubstring and initialize it
with "World".Use the contains() method to check if
concatenated contains searchSubstring.
Step 3 : Print the result (either true or false).
Step 4 : Extract a Substring : Use the substring(6, 11) method
on concatenated to extract characters from index 6 to 10
(since the end index 11 is exclusive).
Step 5 : Store the extracted substring in extractedSubstring.
Step 6 : Print the Extracted Substring
Step 7 : Display the value of extractedSubstring using
System.out.println().

PROGRAM CODE :

public class StringOperations {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String concatenated = str1 + " " + str2;
System.out.println("Concatenated String: " + concatenated);
String searchSubstring = "World";
System.out.println("Contains 'World'? : " +
concatenated.contains(searchSubstring));

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 12

String extractedSubstring = concatenated.substring(6, 11);


System.out.println("Extracted Substring: " + extractedSubstring);
}
}

OUTPUT :

RESULT :
Thus the Java programming used to perform String Operations was
executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 13
EX NO : 07
STRING BUFFER OPERATION
DATE :

AIM :

To develop a Java program to perform string operations using


String Buffer class: Length of a string, Reverse a string, Delete a
substring from the given string.

ALGORITHM :
Step 1: Create a StringBuffer object with an initial string.
Step 2: Append a string to the existing buffer using append().
PAGE NO : 16
Step 3: Insert a string at a specific index using insert(in dex, str).
Step 4: Replace part of the string using replace
(startIndex, endIndex, str).
Step 5: Delete part of the string using delete(startIndex, endIndex).
Step 6: Reverse the string using reverse().
Step 7: Find the length of the buffer using length().

PROGRAM CODE :

public class StringBufferOperations {


public static void main(String[] args) {
StringBuffer str = new StringBuffer("HelloWorld");
System.out.println("Length: " + str.length());
System.out.println("Reversed: " + str.reverse());
str.reverse();
str.delete(5, 10);
System.out.println("After Deletion: " + str);
}
}

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 14

OUTPUT :

RESULT :

Thus the Java program to perform String Buffer Operation was


executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 15
EX NO : 08
MULTI THREAD
DATE :

AIM :

To develop a Java program that implements a multi-thread


application.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 16

ALGORITHM :
Step 1: Create a class that implements Runnable or extends Thread.
Step 2: Override the run() method to define the task to be executed.
Step 3: Create instances of the class for each thread.
Step 4: Start the thread using the start() method.
Step 5: Use join() if you need to wait for a thread to finish.

PROGRAM CODE :

class Thread1 extends Thread {


public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 1: " + i);
}
}
}
class Thread2 extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Thread 2: " + i);
}
}

}
public class MultiThread {
public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
} t2.start();
}

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 16

OUTPUT :

RESULT :

Thus the Java program used to implement Multi thread was executed
successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 17
EX NO : 09
EXCEPTION HANDLING
DATE :

AIM :
To develop a Java program to demonstrate the use of following exceptions:
Arithmetic Exception, Number Format Exception, Array Index Out of
Bound Exception, Negative Array Size Exception.
ALGORITHM :
Step 1: Identify code that may throw exceptions.
Step 2: Wrap the risky code in a try block.
Step 3: Catch specific exceptions using catch blocks.
Step 4: Optionally, use a finally block for cleanup code.
Step 5: Use throw to manually raise an exception.
Step 6: Create custom exceptions by extending the Exception class
(if needed).
Step 7: Use throws in method signatures to declare exceptions.

PROGRAM CODE :
public class ExceptionDemo {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " + e.getMessage());
}
try {
int number = Integer.parseInt("abc");
} catch (NumberFormatException e) {
System.out.println("Caught NumberFormatException: " + e.getMessage());
}
try {
int[] array = {1, 2, 3};
int value = array[5];
} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("CaughtArrayIndexOutOfBoundsException:"+e.getMessage());

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 18

}
try {
int[] array = new int[-5];
} catch (NegativeArraySizeException e) {
System.out.println("Caught NegativeArraySizeException: " + e.getMessage());
}
}
}

OUTPUT :

RESULT :

Thus the Java programming to implement Exception Handling was


executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 19
EX NO : 10
FILE INFORMATION
DATE :

AIM :
To develop 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.
ALGORITHM :
Step 1 : Create a Scanner object for user input.
Step 2 : Prompt the user to enter a file name.
Step 3 : Read the file name from the user.
Step 4 : Create a File object using the given file name.
Step 5 : Check if the file exists using file.exists(), and display the
result.
Step 6 : Check if the file is readable using file.canRead(), and
display the result.
Step 7 : Check if the file is writable using file.canWrite(), and
display the result.
Step 8 : Determine whether the file is a regular file or a directory
using file.isFile(), and display the result.
Step 9 : Get the file size using file.length(), and display it in bytes.

PROGRAM CODE :
import java.io.File;
import java.util.Scanner;
public class FileInfo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter file name: ");
String fileName = scanner.nextLine();
File file = new File(fileName);
System.out.println("File exists: " + file.exists());
System.out.println("File is readable: " + file.canRead());
System.out.println("File is writable: " + file.canWrite());

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 20

System.out.println("File type: " + (file.isFile() ? "File" :


"Directory"));
System.out.println("File length: " + file.length() + "
bytes");
}
}

OUTPUT :

RESULT :

Thus the Java programming for Handling File Information was


executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 21
EX NO : 11
MOUSE EVENTS
DATE :

AIM :
To develop a 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).

ALGORITHM :

Step 1 : Create a class MouseEventDemo that extends Frame.


Step 2 : Initialize a string variable eventName to store the current mouse event.
Step 3 : Set up the frame with : Title:"Mouse Event Demo", Size:400x400,Visibility:true
Step 4 : Add a MouseListener to detect the following events:
o mouseClicked(): Set eventName to "Mouse Clicked" and repaint.
o mousePressed(): Set eventName to "Mouse Pressed" and repaint.
o mouseReleased(): Set eventName to "Mouse Released" & repaint.
o mouseEntered(): Set eventName to "Mouse Entered" and repaint.
o mouseExited(): Set eventName to "Mouse Exited" and repaint.
Step 5 : Add a MouseMotionListener to detect the following events:
o mouseDragged(): Set eventName to "Mouse Dragged" and repaint.
o mouseMoved(): Set eventName to "Mouse Moved" and repaint.
Step 6 : Override the paint() method to:
o Set the font style and size.
o Calculate the center position for displaying text.
o Draw the eventName string in the center of the frame.
o In the main() method, create an instance of MouseEventDemo.

PROGRAM CODE :

import java.awt.*;
import java.awt.event.*;
public class MouseEventDemo extends Frame {
String eventName = "";
public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 400);
setVisible(true);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 22

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();
}
});
addMouseMotionListener(new MouseAdapter() {
public void mouseDragged(MouseEvent e) {
eventName = "Mouse Dragged";
repaint();
}
public void mouseMoved(MouseEvent e) {
eventName = "Mouse Moved";
repaint();
}
});
}
public void paint(Graphics g) {
Font font = new Font("Arial", Font.BOLD, 20);
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
int x = (getWidth() - fm.stringWidth(eventName)) / 2;
int y = getHeight() / 2;
g.drawString(eventName, x, y);
}
public static void main(String[] args) {

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 23

new MouseEventDemo();
}
}

OUTPUT :

RESULT :
Thus the Java programming to handle all Mouse Events was
executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMT OF COMPUTER SCIENCE PAGE NO : 24
EX NO : 12
CALCULATOR
DATE :

AIM :
To develop a Java program that works as a simple calculator.

ALGORITHM :

Step 1 : Create a Scanner object for user input.


Step 2 : Display the calculator menu with the following options:
Addition, Subtraction, Multiplication, Division.
Step 3 : Prompt the user to enter their choice (1-4).
Step 4 : Read and store the user's choice.
Step 5 : Prompt the user to enter the first number.
Step 6 : Read and store the first number.
Step 7 : Prompt the user to enter the second number.
Step 8 : Read and store the second number.
Step 9 : Use a switch statement to perform the selected operation:
Case 1: Add both numbers and display the result.
Case 2: Subtract the second number from the first and
display the result.
Case 3: Multiply both numbers and display the result.
Case 4: If the second number is not zero, perform division
and display the result.
 Otherwise, display an error message:
"Error:Division by zero!".
 Default Case: If the user enters an invalid
choice, display "Invalid choice!".

PROGRAM CODE :
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Simple Calculator");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMT OF COMPUTER SCIENCE PAGE NO : 25

System.out.print("Choose an operation (1-4): ");


int choice = scanner.nextInt();
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
switch (choice) {
case 1:
System.out.println("Result: " + (num1 + num2));
break;
case 2:
System.out.println("Result: " + (num1 - num2));
break;
case 3:
System.out.println("Result: " + (num1 * num2));
break;
case 4:
if (num2 != 0) {
System.out.println("Result: " + (num1 / num2));
} else {
System.out.println("Error: Division by zero!");
}
break;
default:
System.out.println("Invalid choice!");
}
}
}

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 26

OUTPUT :

RESULT :

Thus the Java programming was used to implement the Simple


Calculator was executed Successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 27
EX NO : 13
TRAFFIC LIGHT
DATE :

AIM :
To develop a 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.
ALGORITHM :
Step 1 : Start the program
Step 2 : Create the GUI window (JFrame)
o Set the window title as "Traffic Light".
o Set the window size to 300 × 200 pixels.
o Set the close operation to exit when closed.
Step 3 : Create UI Components
o Create a JLabel to display the traffic signal message.
o Create three JRadioButtons: Red, Yellow, Green.
o Group the radio buttons using ButtonGroup (so only one
button can be selected at a time).
Step 4 : Add Action Listeners for Each Button
If "Red" button is selected:
 Set label text to "STOP".
 Change label color to RED.
If "Yellow" button is selected:
 Set label text to "READY".
 Change label color to YELLOW.
If "Green" button is selected:
 Set label text to "GO".
 Change label color to GREEN.
Step 5 : Add Components to the Panel
o Add the JLabel to display the signal status.
o Add the three JRadioButtons (Red, Yellow, Green) to the
panel.
Step 6 : Add the Panel to the JFrame
o Set the panel layout properly.
o Add all components to the JFrame.
Step 7 : Make the JFrame Visible
o Call setVisible(true) to display the window.
Step 8 : Wait for User Input
o The user selects a radio button, and the label updates
accordingly.
o The program keeps running until the user closes the
window.
Step 9 : Stop the Program.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 28

PROGRAM CODE :

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TrafficLight {
JFrame frame;
JLabel label;
JRadioButton red, yellow, green;
public TrafficLight() {
frame = new JFrame("Traffic Light");
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
label = new JLabel();
label.setFont(new Font("Arial", Font.BOLD, 24));
red = new JRadioButton("Red");
yellow = new JRadioButton("Yellow");
green = new JRadioButton("Green");
ButtonGroup group = new ButtonGroup();
group.add(red);
group.add(yellow);
group.add(green);
red.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("STOP");
label.setForeground(Color.RED);
}
});
yellow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("READY");
label.setForeground(Color.YELLOW);
}
});
green.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setText("GO");
label.setForeground(Color.GREEN);
}
});

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 29

JPanel panel = new JPanel();


panel.add(label);
panel.add(red);
panel.add(yellow);
panel.add(green);
frame.add(panel);
frame.setVisible(true);
}
public static void main(String[] args) {
new TrafficLight();
}
}

OUTPUT :

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 30

RESULT :
Thus the Java programming to implement the Traffic Light
concept was executed Successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 31
EX NO : 14
TEXT EDITOR
DATE :

AIM :

To write a Java program to accept a text and change its size and
font, Include bold, italic options. Use frames and controls.

ALGORITHM :

Step 1 : Start the program.


Step 2 : Create the GUI Window (JFrame)
o Set the window title as "Text Editor".
o Set the window size to 400 × 200 pixels.
o Set the close operation to exit when closed.
o Use FlowLayout for component arrangement.
Step 3 : Create a JTextField for Text Input
o Set default text: "Sample Text".
o Set the default font: Arial, Size 20, Plain style.
Step 4 : Create Font Selection Dropdown (JComboBox)
o Add options: Arial, Times New Roman, Verdana,
Courier New.
o Set "Arial" as the default selection.
Step 5 : Create Size Selection Dropdown (JComboBox)
o Add options: 16, 20, 24, 28, 32.
o Set "20" as the default selection.
Step 6 : Create Bold and Italic Checkboxes (JCheckBox)
o Add a "Bold" checkbox.
o Add an "Italic" checkbox.
Step 7 : Add Event Listeners to All Components
o When the user changes the font, size, bold, or italic
options, update the text field style.
Step 8 : Update Text Style Dynamically
o Retrieve the selected font from the font dropdown.
o Retrieve the selected size from the size dropdown.
o Check if Bold and/or Italic options are selected.
o Apply the selected styles to the text field.
Step 8 : Add Components to the Frame

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 32

o Add the text field, font dropdown, size dropdown,


and checkboxes to the window.
Step 9 : Display the Window
o Set the frame visibility to true.
Step 10 : Wait for User Interaction
o The user selects font, size, or style options, and the
text updates dynamically.
o The program runs continuously until the user
closes the window.
Step 11 : Stop the Program.

PROGRAM CODE :

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class TextEditor {


private JFrame frame;
private JTextField textField;
private JComboBox<String> fontBox, sizeBox;
private JCheckBox boldCheck, italicCheck;

public TextEditor() {
frame = new JFrame("Text Editor");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());

// Text field
textField = new JTextField("Sample Text", 20);
textField.setFont(new Font("Arial", Font.PLAIN, 20));

// Font selection
String[] fonts = {"Arial", "Times New Roman", "Verdana", "Courier New"};
fontBox = new JComboBox<>(fonts);
fontBox.setSelectedItem("Arial");

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 33

// Size selection
String[] sizes = {"16", "20", "24", "28", "32"};
sizeBox = new JComboBox<>(sizes);
sizeBox.setSelectedItem("20");

// Bold and Italic options


boldCheck = new JCheckBox("Bold");
italicCheck = new JCheckBox("Italic");

// Add action listeners to update font


ActionListener updateFont = e -> updateTextStyle();
fontBox.addActionListener(updateFont);
sizeBox.addActionListener(updateFont);
boldCheck.addActionListener(updateFont);
italicCheck.addActionListener(updateFont);

// Add components to frame


frame.add(textField);
frame.add(new JLabel("Font:"));
frame.add(fontBox);
frame.add(new JLabel("Size:"));
frame.add(sizeBox);
frame.add(boldCheck);
frame.add(italicCheck);

// Show frame
frame.setVisible(true);
}

private void updateTextStyle() {


String selectedFont = (String) fontBox.getSelectedItem();
int selectedSize = Integer.parseInt((String) sizeBox.getSelectedItem());
int style = (boldCheck.isSelected() ? Font.BOLD : Font.PLAIN) |
(italicCheck.isSelected() ? Font.ITALIC : Font.PLAIN);

textField.setFont(new Font(selectedFont, style, selectedSize));


}

public static void main(String[] args) {


new TextEditor();

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


DEPARTMENT OF COMPUTER SCIENCE PAGE NO : 34

}
}

OUTPUT :

RESULT :
Thus the Java programming was used to implement the Text
Editor was executed successfully.

ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.


ST.THERESA’S ARTS AND SCIENCE COLLEGE FOR WOMEN,THARANGAMBADI-609313.

You might also like