Java Programming Spiral
Java Programming Spiral
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.
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]();
RESULT :
The above program has executed and the prime numbers printed successfully.
Ex no : 2
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].*;
A[i][k] * B[k][j];
[Link]("Result:");
for (int[] row : C)
row)
[Link]();
}
OUTPUT :
RESULT :
The above program has executed and to multiply the given two matrices printed
successfully.
Ex no : 3
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.
{
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;
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
AIM :
To Write a Java Program to manipulate string using character array.
ALGORITHM:
import [Link];
if ([Link](searchSub))
{
[Link]("Substring \"" + searchSub + "\" found at index: " +
[Link](searchSub));
} else {
if (start >= 0 && end <= [Link]() && start < end)
} else {
[Link]();
}
OUTPUT:
RESULT :
The above program has executed to manipulate string using character array
successfully.
Ex no : 6
AIM :
To Write a Java Program to displays the number of characters, lines and words in a
text
ALGORITHM :
3. Ask the user for a character position and display the character at that position if
valid.
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
AIM :
To Write a Java Program for String operations using stringbuffer class.
ALGORITHM:
SOURCE CODE:
import [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
AIM :
To write a Java Program to implement multithreading for performing multiple tasks
concurrently
ALGORITHM:
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;
}
Cube(int number)
{ [Link] =
number;
}
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 :
{ [Link] = start;
[Link] = end;
{ printNumbers(start, end);
try {
} catch (InterruptedException e)
{ [Link]("Thread interrupted");
[Link]();
[Link]();
}
OUTPUT :
RESULT:
The above program has executed and demonstrated asynchronous execution successfully
using threading in Java.
Ex no : 10
Date:
EXCEPTION
AIM:
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];
try {
} catch (ArithmeticException e)
[Link]());
[Link]();
try {
} catch (NumberFormatException e) {
try {
} catch (ArrayIndexOutOfBoundsException e) {
try {
[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:
SOURCE CODE:
import [Link];
import [Link];
if ([Link]()) {
} else {
[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 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);
}
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 :
SOURCE CODE :
import [Link].*;
import [Link].*;
import [Link].*;
public MouseEventDemo()
{ setTitle("Mouse Event Handler");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
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 SimpleCalculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
[Link](false);
add(display, [Link]);
String[] buttons = {
};
[Link](this);
[Link](button);
add(panel, [Link]);
setVisible(true);
}
if ("0123456789".contains(command))
{ [Link]([Link]() + command);
} else if ("+-*%".contains(command)) {
try {
num1 = [Link]([Link]());
operator = command;
[Link]("");
[Link]("Error");
} else if ([Link]("="))
{ try {
double result = 0;
switch (operator) {
if (num2 == 0) {
[Link]("Divide by 0 Error");
return;
result = num1 %
num2; break;
[Link]([Link] f(result));
[Link]("Error");
} else if ([Link]("C")) {
[Link]("");
operator = "";
num1 = 0;
[Link](SimpleCalculator::new);
}
OUTPUT :
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 TrafficLightSimulator()
{ setTitle("Traffic Light
Simulator");
setSize(350, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
add(messageLabel, [Link]);
[Link](redButton);
[Link](yellowButton);
[Link](greenButton);
[Link](redButton);
[Link](yellowButton);
[Link](greenButton);
// Add listeners
[Link](this);
[Link](this);
[Link](this);
add(radioPanel, [Link]);
setVisible(true);
@Override
{ if ([Link]()) {
[Link]("Stop");
[Link]([Link]);
} else if ([Link]()) {
[Link]("Ready");
[Link]([Link]);
} else if ([Link]()) {
[Link]("Go");
[Link]([Link]());
} else {
[Link]("");
[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;
{ [Link] = brand;
[Link] = ram;
void displaySpecs()
{ double weight;
[Link] = weight;
void showDetails() {
[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;
[Link] = studentId;
}
void displayStudentInfo()
}
// Derived class 1
class UndergraduateStudent extends Student
{ String 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);
}
}
[Link]("\n--------------------\n");
}
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];
{ [Link] = name;
[Link] = age;
}
public void displayPerson()
package [Link];
import [Link];
{ super(name, age);
[Link] = studentId;
displayPerson();
// File: [Link]
import [Link];
public class Main {
[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 {
{ [Link] = radius;
{ [Link] = width;
[Link] = height;
}
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 Library {
}
// Implementation of Library interface
[Link](bookName);
{ if ([Link](bookName)) {
[Link](bookName);
} else {
[Link](bookName);
}
// Main class with menu
while (true) {
[Link]("4. Exit");
switch (choice) {
case 1:
[Link](addBookName);
break;
case 2:
[Link]("Enter book name to issue: ");
[Link](issueBookName, userName);
break;
case 3:
[Link](returnBookName);
break;
case 4:
[Link]();
[Link](0);
default:
} }}
OUTPUT:
RESULT :
The above program has executed successfully and managed library operations using
interfaces to implement abstraction.