0% found this document useful (0 votes)
3 views77 pages

Java Programming Spiral

The document outlines various Java programming exercises, including implementations for prime number generation, matrix multiplication, text statistics, random number generation, string manipulation, multithreading, and more. Each exercise includes an aim, algorithm, source code, and execution results. The exercises demonstrate fundamental programming concepts and Java class usage.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views77 pages

Java Programming Spiral

The document outlines various Java programming exercises, including implementations for prime number generation, matrix multiplication, text statistics, random number generation, string manipulation, multithreading, and more. Each exercise includes an aim, algorithm, source code, and execution results. The exercises demonstrate fundamental programming concepts and Java class usage.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

[Link] DATE TITLE PG.

NO SIGN

1
PRIME NUMBERS
2
MULTIPLY TWO GIVEN MATRICES
3
DISPLAYS THE NUMBER OF CHARACTERS
LINES AND WORDS IN A TEXT
4
RANDOM NUMBERS BETWEEN TWO GIVEN
LIMITS USING RANDOM CLASS
5
STRING MANIPULATION USING CHARACTER
ARRAY
6
STRING OPERATIONS USING STRING CLASS
7
STRING OPERATIONS USING STRINGBUFFER
CLASS
8
MULTITHREADED JAVA PROGRAM
9
THREADING PROGRAM(ASYNCHRONOUSLY)
10 EXCEPTION

11
DISPLAY FILE INFORMATION BASED ON USER
INPUT
12
TEXT EDITOR USING FRAMES AND CONTROLS
13
MOUSE EVENTS
14
SIMPLE CALCULATOR
15
TRAFFIC LIGHT STIMULATOR
16
SINGLE INHERITANCE
17
STUDENT DETAILS USING HIERARCHICAL
INHERITANCE
18
STUDENT INFORAMTION USING PACKAGE
19
INTERFACES
20 LIBRARY MANAGEMENT SYSTEM USING
INTERFACES
Ex no : 1
PRIME NUMBERS
Date:

AIM :
To Write a Java Program For Printing Prime Numbers

ALGORITHM:
1. Input an integer n from the user.
2. Loop from 2 to n.

3. For each number i, check if i is prime using a helper function.


4. In the helper, test divisibility from 2 to √i.
5. Print i if prime; skip if not.
SOURCE CODE :

Import [Link].*;
import
[Link]
; public class
Primes {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter an integer: ");
int n = [Link]();

for (int i = 2; i <= n; i++) {


if (isPrime(i)) [Link](i + " ");
}
}
static boolean isPrime(int num) {
for (int j = 2; j * j <= num; j++)
{ if (num % j == 0) return false;
}
return num > 1;
}
}
OUTPUT:

RESULT :
The above program has executed and the prime numbers printed successfully.
Ex no : 2

Date: MULTIPLY TWO GIVEN MATRICES

AIM :
To Write a Java Program to multiply given two matrices.

ALGORITHM :
1. Take two matrices A (m×n) and B (n×p) as input.
2. Create a result matrix C (m×p) initialized to 0.
3. Loop through each row i of A and each column j of B.
4. For each element C[i][j], compute the sum of A[i][k] * B[k][j] for all k.
5. Print the result matrix C.
SOURCE CODE :

Import [Link].*;

public class MatrixMultiply {

public static void main(String[] args)

{ int[][] A = { {1, 2}, {3, 4} };

int[][] B = { {5, 6}, {7, 8} };

int[][] C = new int[2][2];

for (int i = 0; i < 2; i++)

for (int j = 0; j < 2; j++)

for (int k = 0; k < 2; k++) C[i][j] +=

A[i][k] * B[k][j];

[Link]("Result:");
for (int[] row : C)

{ for (int val :

row)

[Link](val + " ");

[Link]();

}
OUTPUT :

RESULT :
The above program has executed and to multiply the given two matrices printed

successfully.
Ex no : 3

Date: DISPLAYS THE NUMBER OF CHARACTERS, LINES


AND WORDS IN A TEXT

AIM :
To Write a Java Program to displays the number of characters, lines and words in a
text.

ALGORITHM :
1. Initialize counters: lines = 0, words = 0, characters = 0.
2. Read text line by line until a sentinel value (e.g., "END").

3. For each line: increment lines, add [Link]() to characters, and add
[Link]("\\s+") length to words.
4. Skip word count for empty lines.

5. Output the values of lines, words, and characters.


SOURCE CODE :

import [Link]; public class TextStats

{
public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
StringBuilder text = new StringBuilder();
[Link]("Enter text (type 'END' on a new line to finish):");
int lines = 0;
while (true) {
String line = [Link]();
if ([Link]("EN D")) break; [Link](line).append("\n"); lines++;
}
String allText = [Link](); int characters = [Link]();
int words = [Link]().isEmpty() ? 0 : [Link]().split("\\s+").length;

[Link]("Lines: " + lines);


[Link]("Words: " + words);
[Link]("Characters: " + characters);
}
}
OUTPUT :

RESULT :
The above program has executed and displays the number of characters, lines and
words in a text successfully.
Ex no : 4

Date:
RANDOM NUMBERS BETWEEN TWO GIVEN
LIMITS USING RANDOM CLASS

AIM :
To Write a Java Program to displays random numbers between two given limits
using random class.

ALGORITHM :
1. Input lower and upper limits.
2. Generate random number: random = lower + [Link](upper - lower + 1).
3. Calculate range thresholds: low, mid, high.
4. If random < low → print "Low range", else if < mid → print "Medium range", else → print
"High range".
5. End.
SOURCE CODE :

import [Link];
import [Link];
public class RandomRangeMessage
{ public static void main(String[] args)
{
Scanner sc = new Scanner([Link]);
Random rand = new Random();
[Link]("Enter lower limit: ");
int lower = [Link]();
[Link]("Enter upper limit: ");
int upper = [Link]();
int randomNum = [Link](upper - lower + 1) + lower;
[Link]("Random number: " + randomNum);
if (randomNum < lower + (upper - lower) / 3) {
[Link]("Low range value.");
} else if (randomNum < lower + 2 * (upper - lower) / 3)
{ [Link]("Medium range value.");
} else {
[Link]("High range value.");
}
[Link]();
}
}
OUTPUT :

RESULT :
The above program has executed and displays random numbers between two given
limits using random class successfully.
Ex no : 5

Date: STRING MANIPULATION USING CHARACTER ARRAY

AIM :
To Write a Java Program to manipulate string using character array.

ALGORITHM:

1. Input two strings from the user.


2. Concatenate the two strings using the + operator.
3. Input a substring and search it using indexOf() or contains().
4. Input start and end indices and extract substring using substring(start, end).
5. Display the results of concatenation, search, and extracted substring.
SOURCE CODE:

import [Link];

public class StringOperations {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter the first string: ");

String str1 = [Link]();

[Link]("Enter the second string: ");

String str2 = [Link]();

String concatenated = str1 + str2; [Link]("\

nConcatenated String: " + concatenated);

[Link]("\nEnter a substring to search in concatenated string: ");

String searchSub = [Link]();

if ([Link](searchSub))
{
[Link]("Substring \"" + searchSub + "\" found at index: " +
[Link](searchSub));

} else {

[Link]("Substring not found.");

[Link]("\nEnter the starting index to extract substring: ");

int start = [Link]();

[Link]("Enter the ending index: ");

int end = [Link]();

if (start >= 0 && end <= [Link]() && start < end)

{ String extracted = [Link](start, end);


[Link]("Extracted Substring: " + extracted);

} else {

[Link]("Invalid indices for substring extraction.");

[Link]();

}
OUTPUT:

RESULT :
The above program has executed to manipulate string using character array
successfully.
Ex no : 6

Date: STRING OPERATIONS USING STRING CLASS

AIM :
To Write a Java Program to displays the number of characters, lines and words in a
text

ALGORITHM :

1. Read two input strings from the user.

2. Calculate and display the length of the first string.

3. Ask the user for a character position and display the character at that position if
valid.

4. Concatenate both strings manually using character arrays.

5. Convert the concatenated character array back to a string and display it.

SOURCE CODE :

import [Link];
public class StringManipulation {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the first string: ");
String str1 = [Link]();
char[] charArray1 = [Link]();
int length = 0;
for (char c : charArray1) {
length++;

}
[Link]("Length of the first string: " + length);
[Link]("Enter the position to find character (0 to " + (length - 1) + "):
");
int position = [Link]();
[Link]();
if (position >= 0 && position < length) {
[Link]("Character at position " + position + ": " +
charArray1[position]);
}
else {
[Link]("Invalid position!");
}
[Link]("Enter the second string: ");
String str2 = [Link]();
char[] charArray2 = [Link]();
char[] concatenated = new char[[Link] + [Link]];
int index = 0;
for (char c : charArray1) {
concatenated[index++] = c;
}
for (char c : charArray2)
{ concatenated[index++] = c;
}
String result = new String(concatenated);
[Link]("Concatenated string: " + result);
[Link]();
}
}
OUTPUT :

RESULT :
The above program has executed and performed various string operations successfully
using the String class.
Ex no : 7

Date: STRING OPERATIONS USING STRINGBUFFER CLASS

AIM :
To Write a Java Program for String operations using stringbuffer class.

ALGORITHM:

1. Input a string and create a StringBuffer object.


2. Find and display the length using .length().
3. Reverse the string using .reverse() and display it.
4. Input start and end indices to delete a substring.
5. Delete the substring using .delete(start, end) and display the result.

SOURCE CODE:
import [Link];

public class StringBufferOperations


{ public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);

// Input string from user


[Link]("Enter a string: ");
String input = [Link]();

// Create a StringBuffer object


StringBuffer buffer = new StringBuffer(input);

// 1. Length of the string


[Link]("\nLength of the string: " + [Link]());

// 2. Reverse the string


StringBuffer reversed = new StringBuffer(buffer).reverse();
[Link]("Reversed string: " + reversed);
// 3. Delete a substring
[Link]("\nEnter start index to delete substring: ");
int start = [Link]();
[Link]("Enter end index to delete substring: ");
int end = [Link]();

if (start >= 0 && end <= [Link]() && start < end)
{ [Link](start, end);
[Link]("String after deletion: " + buffer);
} else {
[Link]("Invalid indices for deletion.");
}

[Link]();
}
}
OUTPUT :

RESULT :
The above program has executed and performed various string operations successfully
using the StringBuffer class.
Ex no : 8

Date: MULTITHREADED JAVA PROGRAM

AIM :
To write a Java Program to implement multithreading for performing multiple tasks
concurrently

ALGORITHM:

1. Start a thread to generate a random number every second (10 times).


2. For each number, check if it is even or odd.
3. If even, start a thread to calculate and print its square.
4. If odd, start a thread to calculate and print its cube.
5. Repeat until 10 numbers are processed.

SOURCE CODE :

import [Link];
class NumberGenerator extends Thread
{ public void run() {
Random rand = new Random();
for (int i = 1; i <= 10; i++) { // Run 10 times
int num = [Link](100); // Random number between 0–99 [Link]("\
nGenerated Number: " + num);

if (num % 2 == 0) {
new Square(num).start();
} else {
new Cube(num).start();
}

try {
[Link](1000); // Wait for 1 second
} catch (InterruptedException e)
{ [Link]("Thread interrupted.");
}
}
}
}
class Square extends Thread {
int number;
Square(int number)
{ [Link] =
number;
}

public void run() {


int square = number * number;
[Link]("Square of " + number + " is: " + square);
}
}
class Cube extends Thread
{ int number;

Cube(int number)
{ [Link] =
number;
}

public void run() {


int cube = number * number * number;
[Link]("Cube of " + number + " is: " + cube);
}
}
public class MultiThreadExample {
public static void main(String[] args) {
NumberGenerator generator = new NumberGenerator();
[Link](); // Start the number generator thread
}
}
OUTPUT :

RESULT :
The above program has executed and demonstrated multithreading successfully using the
Thread class.
Ex no : 9
THREADING PROGRAM(ASYNCHRONOUSLY)
Date:

AIM :
To Write a Java Program to demonstrate multithreading by executing tasks
asynchronously.

ALGORITHM:

1. Create a runnable class with a method to print numbers from a given start to end.
2. Instantiate two threads using this runnable class with ranges 1–10 and 90–100.
3. Start both threads.
4. Each thread calls the common method to print its range of numbers.
5. Threads run asynchronously and print numbers concurrently.

SOURCE CODE :

class NumberPrinter implements Runnable

{ private int start;

private int end;

NumberPrinter(int start, int end)

{ [Link] = start;

[Link] = end;

public void run()

{ printNumbers(start, end);

private void printNumbers(int from, int to)

{ for (int i = from; i <= to; i++) {


[Link]([Link]().getName() + ": " + i);

try {

[Link](100); // Sleep to simulate asynchronous behavior

} catch (InterruptedException e)

{ [Link]("Thread interrupted");

public class ThreadExample {

public static void main(String[] args) {

Thread thread1 = new Thread(new NumberPrinter(1, 10), "Thread1");

Thread thread2 = new Thread(new NumberPrinter(90, 100), "Thread2");

[Link]();

[Link]();

}
OUTPUT :

RESULT:
The above program has executed and demonstrated asynchronous execution successfully
using threading in Java.
Ex no : 10

Date:
EXCEPTION

AIM:

To Write a Java Program to demonstrate multiple exception handling.

ALGORITHM:

1. Prompt the user to enter two integers and perform division to demonstrate
ArithmeticException (e.g., division by zero).
2. Prompt the user to enter a string and convert it to an integer to show
NumberFormatExce ption if the input is not a valid number.
3. Create an array and access an invalid index to cause
ArrayIndexOutOfBounds Exception.
4. Attempt to create an array with a negative size to trigger
NegativeArraySizeException.
5. Use try-catch blocks to handle and display messages for each exception.

SOURCE CODE:

import [Link];

public class ExceptionDemo {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

try {

[Link]("Enter numerator: ");

int num = [Link]();

[Link]("Enter denominator: ");

int den = [Link]();


int result = num / den; // May throw ArithmeticException

[Link]("Result: " + result);

} catch (ArithmeticException e)

{ [Link]("ArithmeticException caught: " +

[Link]());

[Link]();

try {

[Link]("Enter a number as string: ");

String str = [Link]();

int val = [Link](str); // May throw NumberFormatException

[Link]("Parsed integer: " + val);

} catch (NumberFormatException e) {

[Link]("N umberFormatException caught: Invalid number


format");

try {

int[] arr = new int[3];

[Link](arr[5]); // Invalid index

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("ArrayIndexO utOfBoundsException caught: " +


[Link]());

try {

int size = -5;

int[] negativeArray = new int[size]; // Invalid size


} catch (NegativeArraySizeException e) {

[Link]("NegativeArraySizeException caught: " +


[Link]());

[Link]();

}
OUTPUT :

RESULT :
The above program has executed and handled exceptions successfully using try, catch,
and finally blocks.
Ex no : 11
DISPLAY FILE INFORMATION BASED ON USER INPUT
Date:

AIM :
T o Write a Java Program to display file information based on user input.

ALGORITHM:

1. Prompt and read the file name from the user.


2. Create a File object using the given name.
3. Check if the file exists using [Link]().
4. If it exists, display file properties like readability, writability, type, and length.
5. If it doesn't exist, inform the user the file was not found.

SOURCE CODE:
import [Link];

import [Link];

public class FileInfo {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter the file name (with path if needed): ");

String fileName = [Link]();

File file = new File(fileName);

if ([Link]()) {

[Link]("File exists: Yes");

[Link]("Readable: " + ([Link]() ? "Yes" : "No"));

[Link]("Writable: " + ([Link]() ? "Yes" : "No"));

[Link]("Type: " + ([Link]() ? "Regular File" :


([Link]() ? "Directory" : "Unknown")));

[Link]("File length (in bytes): " + [Link]());

} else {

[Link]("File does not exist.");

[Link]();

}
OUTPUT:

RESULT :
The above program has executed successfully and displayed the file information based on
the user’s input.
Ex no : 12
TEXT EDITOR USING FRAMES AND CONTROLS
Date:

AIM :
To Write a Java Program to create a text editor using frames and controls.

ALGORITHM:
1. Initialize GUI with JTextPane, font controls (JComboBox for font/size), and
style options (JCheckBox for bold/italic).
2. Capture user actions on controls using ActionListener.
3. Get selected text range using getSelectionStart() and getSelectionEnd().
4. Build and apply style attributes (SimpleAttributeSet) based on selected font,
size, and styles.
5. Apply attributes to the selected text using
[Link]().

SOURCE CODE:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

public class RichTextEditor extends JFrame implements ActionListener


{ private JTextPane textPane;
private JComboBox<String> fontBox, sizeBox;
private JCheckBox boldCheck, italicCheck;

public RichTextEditor()
{ setTitle("Selective Text Styler");
setSize(600, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// TextPane with styled document
textPane = new JTextPane();
[Link]("Select text and style it...");
add(new JScrollPane(textPane), [Link]);

// Control panel
JPanel controlPanel = new JPanel();

// Font options
String[] fonts =
[Link]().getAvailableFontFamilyNames();
fontBox = new JComboBox<>(fonts);
[Link]("Serif");

// Font size
String[] sizes = { "12", "14", "16", "18", "20", "24", "28", "32" };
sizeBox = new JComboBox<>(sizes);
[Link]("16");
// Bold and Italic checkboxes
boldCheck = new JCheckBox("Bold");
italicCheck = new JCheckBox("Italic");

// Add listeners
[Link](this);
[Link](this);
[Link](this);
[Link](this);

// Add components
[Link](new JLabel("Font:"));
[Link](fontBox);
[Link](new JLabel("Size:"));
[Link](sizeBox);
[Link](boldCheck);
[Link](italicCheck);

add(controlPanel, [Link]);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
// Get selected text range
int start = [Link]();
int end = [Link]();
if (start == end) return; // No selection
StyledDocument doc = [Link]();
// Build new attribute set
SimpleAttributeSet attrs = new SimpleAttributeSet();
String selectedFont = (String) [Link]();
int fontSize = [Link]((String) [Link]());
[Link](attrs, selectedFont);
[Link](attrs, fontSize);
[Link](attrs, [Link]());
[Link](attrs, [Link]());
[Link](start, end - start, attrs, false);
}

public static void main(String[] args) {


[Link](() -> new RichTextEditor());
}
}
OUTPUT :

RESULT :
The above program has executed successfully and provided a functional text editor
interface using frames and controls.
Ex no : 13

Date:
MOUSE EVENTS

AIM :
To Write a Java Program to demonstrate mouse events.

ALGORITHM :

1. Create a window (JFrame) with a custom panel to display messages.


2. Add a MouseAdapter to the panel to handle mouse events (click, press, release,
enter, exit)
3. Update the event name string based on the triggered mouse event.
4. Call repaint() to redraw the panel with the updated event name.
5. Display the event name centered in the panel using custom painting
(paintComponent).

SOURCE CODE :

import [Link].*;
import [Link].*;
import [Link].*;

public class MouseEventDemo extends JFrame


{ private String eventName = "No Event Yet";

public MouseEventDemo()
{ setTitle("Mouse Event Handler");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);

// Custom panel to draw event name


JPanel panel = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
[Link](g);
[Link](new Font("Arial", [Link], 20));
FontMetrics fm = [Link]();
int x = (getWidth() - [Link](eventName)) / 2;
int y = (getHeight() / 2) + [Link]() / 2;
[Link](eventName, x, y);
}
};
[Link]([Link]);

// MouseAdapter handles all events


[Link](new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
eventName = "Mouse Clicked";
[Link]();
}

public void mousePressed(MouseEvent e)


{ eventName = "Mouse Pressed";
[Link]();
}

public void mouseReleased(MouseEvent e)


{ eventName = "Mouse Released";
[Link]();
}

public void mouseEntered(MouseEvent e)


{ eventName = "Mouse Entered";
[Link]();
}

public void mouseExited(MouseEvent e)


{ eventName = "Mouse Exited";
[Link]();
}
});

add(panel);
setVisible(true);
}
public static void main(String[] args) {
[Link](MouseEventDemo::new);
}
}
OUTPUT :
RESULT :
The above program has executed successfully and handled mouse events using event
listeners to respond to user actions.
Ex no : 14

Date:
SIMPLE CALCULATOR

AIM :
To Write a Java Program to create a simple calculator.

ALGORITHM :

1. Create GUI components – a JTextField for display and buttons for digits (0–9) and
operations (+, −, *, %, =, C).
2. Arrange buttons in a GridLayout within a panel for organized layout.
3. Add action listeners to buttons to update the text field or perform calculations.
4. Evaluate expressions when = is pressed, handling operations accordingly.
5. Handle exceptions like divide-by- zero or invalid input using try-catch blocks.

SOURCE CODE :

import [Link].*;

import [Link].*;

import [Link].*;

public class SimpleCalculator extends JFrame implements ActionListener

{ private JTextField display;

private String operator = "";

private double num1 = 0;

public SimpleCalculator() {

setTitle("Simple Calculator");

setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(new BorderLayout());

display = new JTextField();

[Link](false);

[Link](new Font("Arial", [Link], 24));

add(display, [Link]);

JPanel panel = new JPanel(new GridLayout(4, 4, 5, 5));

String[] buttons = {

"7", "8", "9", "+",

"4", "5", "6", "-",

"1", "2", "3", "*",

"0", "C", "%", "="

};

for (String text : buttons) {

JButton button = new JButton(text);

[Link](new Font("Arial", [Link], 20));

[Link](this);

[Link](button);

add(panel, [Link]);

setVisible(true);
}

public void actionPerformed(ActionEvent e)

{ String command = [Link]();

if ("0123456789".contains(command))

{ [Link]([Link]() + command);

} else if ("+-*%".contains(command)) {

try {

num1 = [Link]([Link]());

operator = command;

[Link]("");

} catch (NumberFormatException ex) {

[Link]("Error");

} else if ([Link]("="))

{ try {

double num2 = [Link]([Link]());

double result = 0;

switch (operator) {

case "+": result = num1 + num2; break;

case "-": result = num1 - num2; break;

case "*": result = num1 * num2; break;


case "%":

if (num2 == 0) {

[Link]("Divide by 0 Error");

return;

result = num1 %

num2; break;

[Link]([Link] f(result));

} catch (Exception ex) {

[Link]("Error");

} else if ([Link]("C")) {

[Link]("");

operator = "";

num1 = 0;

public static void main(String[] args) {

[Link](SimpleCalculator::new);

}
OUTPUT :

While adding 100+200 =300


While subtracting 300-100=200

While multiplying 250*2=500


While finding percentage 250%100=50.0

RESULT :
The above program has executed successfully and performed basic arithmetic operations
using the calculator interface.
Ex no : 15

Date:
TRAFFIC LIGHT STIMULATOR

AIM :
To Write a Java Program to simulate a traffic light system.

ALGORITHM :

1. Create a window with a label for messages and three radio buttons (Red, Yellow,
Green).
2. Group the radio buttons so only one can be selected at a time.
3. Add event listeners to detect which button is selected.
4. When a button is selected, update the label with the appropriate message and
color.
5. Initially show no message until a button is selected.

SOURCE CODE :

import [Link].*;

import [Link].*;

import [Link].*;

public class TrafficLightSimulator extends JFrame implements ActionListener

{ private JLabel messageLabel;

private JRadioButton redButton, yellowButton, greenButton;

private ButtonGroup group;

public TrafficLightSimulator()

{ setTitle("Traffic Light

Simulator");
setSize(350, 200);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(new BorderLayout());

// Message label (initially empty)

messageLabel = new JLabel("", [Link] TER);

[Link](new Font("Arial", [Link], 24));

add(messageLabel, [Link]);

// Panel for radio buttons

JPanel radioPanel = new JPanel();

redButton = new JRadioButton("Red");

yellowButton = new JRadioButton("Yellow");

greenButton = new JRadioButton("Green");

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

group = new ButtonGroup();

[Link](redButton);

[Link](yellowButton);

[Link](greenButton);

// Add buttons to panel

[Link](redButton);

[Link](yellowButton);
[Link](greenButton);

// Add listeners

[Link](this);

[Link](this);

[Link](this);

add(radioPanel, [Link]);

setLocationRelativeTo(null); // Center window

setVisible(true);

@Override

public void actionPerformed(ActionEvent e)

{ if ([Link]()) {

[Link]("Stop");

[Link]([Link]);

} else if ([Link]()) {

[Link]("Ready");

[Link]([Link]);

} else if ([Link]()) {

[Link]("Go");

[Link]([Link]());
} else {

[Link]("");

public static void main(String[] args) {

[Link](TrafficLightSimulator::new);

}
OUTPUT:
RESULT :
The above program has executed successfully and simulated the operation of a traffic
light system accurately
Ex no : 16

Date:
SINGLE INHERITANCE

AIM :
To Write a Java Program to display t h e s p e c i f i c a t i o n s o f a c o m p u t e r a n d a
laptop using single inheritance.

ALGORITHM :

1. Define a base class Computer with attributes: brand, ram, and a method
displaySpecs() to print them.
2. Define a subclass Laptop that inherits from Computer, adds attribute weight, and a
method showDetails() to display all details.
3. In the main method, create an object of Laptop with values ("Dell", 16, 1.8).
4. Call the method showDetails() to print brand, RAM, and weight of the laptop.
5. Stop

SOURCE CODE :
class Computer

{ String brand;

int ram;

Computer(String brand, int ram)

{ [Link] = brand;

[Link] = ram;

void displaySpecs()

{ [Link](&quot;Brand: &quot; + brand);

[Link](&quot;RAM: &quot; + ram + &quot;GB&quot;);


}

class Laptop extends Computer

{ double weight;

Laptop(String brand, int ram, double weight)

{ super(brand, ram); // Call parent constructor

[Link] = weight;

void showDetails() {

displaySpecs(); // Reuse parent method

[Link](&quot;Weight: &quot; + weight + &quot; kg&quot;);

public class InheritanceDemo {

public static void main(String[] args) {

Laptop myLaptop = new Laptop(&quot;Dell&quot;, 16, 1.8);

[Link]();

}
OUTPUT :

RESULT :
The program executed successfully and demonstrated inheritance. Laptop details (brand,
RAM, and weight) were displayed correctly.
Ex no : 17

Date:
STUDENT DETAILS USING HIERARCHICAL INHERITANCE

AIM :
To Write a Java Program to display student details using hierarchical inheritance.

ALGORITHM:

1. Define a base class Student with attributes: name, age, studentId and a method to
display these details.
2. Define a subclass UndergraduateStudent that inherits from Student, adds major, and a
method to display all undergraduate student info.
3. Define another subclass GraduateStudent that inherits from Student, adds thesisTitle,
and a method to display all graduate student info.
4. In the main method, create objects for UndergraduateStudent and GraduateStudent
with appropriate data.
5. Call their display methods to print the details for each student type.

SOURCE CODE:
class Student {
String name;
int age;

String studentId;

Student(String name, int age, String studentId)


{ [Link] = name;
[Link] = age;

[Link] = studentId;
}
void displayStudentInfo()

{ [Link]("Name: " + name);

[Link]("Age: " + age);

[Link]("Student ID: " + studentId);


}

}
// Derived class 1
class UndergraduateStudent extends Student

{ String major;

UndergraduateStudent(String name, int age, String studentId, String major)


{ super(name, age, studentId);
[Link] = major;

void displayUndergraduateInfo() {
displayStudentInfo();
[Link]("Major: " + major);
}

// Derived class 2
class postGraduateStudent extends Student
{ String ProjectTitle;
postGraduateStudent(String name, int age, String studentId, String ProjectTitle) {
super(name, age, studentId);
[Link] = ProjectTitle;
}

void displayGraduateInfo() {
displayStudentInfo();
[Link]("Project Title: " +ProjectTitle);

}
}

public class HierarchicalInheritanceDemo


{ public static void main(String[] args) {
UndergraduateStudent ugStudent = new UndergraduateStudent("Emily Clark",
19, "UG2025", "Biology");
[Link]("Undergraduate Student Info:");
[Link]();

[Link]("\n--------------------\n");

postGraduateStudent gradStudent = new postGraduateStudent("David Lee", 26,


"GR2021", "Machine Learning in Healthcare");

[Link]("postGraduate Student Info:");


[Link]();
}

}
OUTPUT :

RESULT :
The above program has executed successfully and demonstrated hierarchical inheritance
by displaying student details
Ex no : 18
DISPLAYING STUDENT INFORAMTION USING PACKAGE
Date:

AIM :
To Write a Java Program to display student information using packages.

ALGORITHM:

1. Start the program and define a Person class in the [Link] package with
attributes name and age, and a method to display them.
2. Create a Student class in the [Link] package that inherits from Person and
includes an additional attribute studentId with a method to display all details.
3. Import the Student class into the Main class.
4. Create a Student object with name, age, and student ID, then call the method to
display the student's information.
5. End the program.

SOURCE CODE:
package [Link];

public class Person {

protected String name;

protected int age;

public Person(String name, int age)

{ [Link] = name;

[Link] = age;

}
public void displayPerson()

{ [Link]("Name: " + name);

[Link]("Age: " + age);

package [Link];

import [Link];

public class Student extends Person

{ private String studentId;

public Student(String name, int age, String studentId)

{ super(name, age);

[Link] = studentId;

public void displayStudent() {

displayPerson();

[Link]("Student ID: " + studentId);

// File: [Link]

import [Link];
public class Main {

public static void main(String[] args) {

Student s = new Student("Alice Walker", 21, "S1001");

[Link]();

}}

}
OUTPUT :

RESULT :
The above program has executed successfully and displayed student information by
utilizing Java packages for better organization
Ex no : 19 INTERFACE
Date:

AIM :
To Write a Java Program to calculate the area of different shapes using interfaces.

ALGORITHM:
1. Start the program and define a Library interface with methods for adding, issuing, and
returning books.

2. Create a CityLibrary class that implements the Library interface using an ArrayList to
store books.

3. Implement the methods to add, issue (remove), and return (add back) books.

4. In the main() method, display a menu to perform operations based on user choice.

5 Execute the selected operation in a loop until the user chooses to exit the program.

SOURCE CODE :
interface Shape {

double area(); // Method to compute area

class Circle implements Shape

{ private double radius;

public Circle(double radius)

{ [Link] = radius;

public double area() {

return [Link] * radius * radius;


}

class Rectangle implements Shape

{ private double width;

private double height;

public Rectangle(double width, double height)

{ [Link] = width;

[Link] = height;

public double area() {

return width * height;

public class Main {

public static void main(String[] args)

{ Shape circle = new Circle(3.5);

Shape rectangle = new Rectangle(4.0, 5.0);

[Link]("Area of Circle: " + [Link]());

[Link]("Area of Rectangle: " + [Link]());

}
OUTPUT:

RESULT:
The program executed successfully and demonstrated the use of interfaces in Java.
Ex no : 20
LIBRARY MANAGEMENT SYSTEM USING INTERFACE IN
Date: JAVA

AIM :
To Write a Java Program to implement a Library Management System using
interfaces.

ALGORITHM:

1. Start the program and define a Library interface with methods for adding, issuing,
and returning books.
2. Create a CityLibrary class that implements the Library interface using an
ArrayList to store books.
3. Implement the methods to add, issue (remove), and return (add back) books.
4. In the main() method, display a menu to perform operations based on user choice.
5. Execute the selected operation in a loop until the user chooses to exit the program.

SOURCE CODE:
import [Link];

import [Link];

// Interface for Library operations

interface Library {

void addBook(String bookName);

void issueBook(String bookName, String userName);

void returnBook(String bookName);

}
// Implementation of Library interface

class CityLibrary implements Library {

private ArrayList<String> books = new ArrayList<>();

public void addBook(String bookName) {

[Link](bookName);

[Link]("\"" + bookName + "\" added to the library.");

public void issueBook(String bookName, String userName)

{ if ([Link](bookName)) {

[Link](bookName);

[Link]("\"" + bookName + "\" issued to " + userName + ".");

} else {

[Link]("Sorry, \"" + bookName + "\" is not available.");

public void returnBook(String bookName) {

[Link](bookName);

[Link]("\"" + bookName + "\" returned to the library.");

}
// Main class with menu

public class LibraryDemo {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

Library library = new CityLibrary();

while (true) {

[Link]("\n====== Library Menu ======");

[Link]("1. Add Book");

[Link]("2. Issue Book");

[Link]("3. Return Book");

[Link]("4. Exit");

[Link]("Choose an option (1-4): ");

int choice = [Link]();

[Link](); // Consume newline

switch (choice) {

case 1:

[Link]("Enter book name to add: ");

String addBookName = [Link]();

[Link](addBookName);

break;

case 2:
[Link]("Enter book name to issue: ");

String issueBookName = [Link]();

[Link]("Enter user name: ");

String userName = [Link]();

[Link](issueBookName, userName);

break;

case 3:

[Link]("Enter book name to return: ");

String returnBookName = [Link]();

[Link](returnBookName);

break;

case 4:

[Link]("Exiting Library System. Goodbye!");

[Link]();

[Link](0);

default:

[Link]("Invalid choice. Try again.");

} }}
OUTPUT:

RESULT :
The above program has executed successfully and managed library operations using
interfaces to implement abstraction.

You might also like