PROGRAM 1:(PRIME NUMBERS)
AIM:
To find and display all prime numbers less than a given number entered by the user.
ALGORITHM:
Step 1: Start
Begin the program execution.
Step 2: Input the number
Prompt the user to enter a number n.
This number will act as the upper limit.
We will find all prime numbers less than n.
Step 3: Loop through numbers
Use a for loop to check each number i starting from 2 up to n-1.
Why start from 2? Because 1 is not considered a prime number.
Step 4: Assume the number is prime
For each number i, set a flag variable p = 0.
This flag will help us decide whether the number is prime or not.
Step 5: Check divisibility
Use another for loop to check if i is divisible by any number between 2 and i-1.
If i % j == 0, then i is divisible by j.
In that case, set p = 1 (meaning i is not prime).
Step 6: Print prime numbers
After checking divisibility, if p remains 0, it means no divisor was found.
Therefore, i is prime → print the number.
Step 7: End
Continue the process until all numbers less than n are checked.
End the program.
PROGRAM 2:(Matrix Multiplication)
AIM:
To write a Java program that multiplies two square matrices entered by the user and prints the
resulting product matrix.
ALGORITHM:
1. Start the program.
2. Input the size of the matrices
o Read an integer n from the user.
o Both matrices will be of order n × n.
3. Declare matrices
o Create three 2D arrays:
a[n][n] → first matrix
b[n][n] → second matrix
c[n][n] → product matrix (initialized to zero).
4. Read elements of the first matrix
o Use nested loops to input elements row by row into a.
5. Read elements of the second matrix
o Use nested loops to input elements row by row into b.
6. Perform matrix multiplication
o Use three nested loops:
Outer loop (i) → iterates over rows of a.
Middle loop (j) → iterates over columns of b.
Inner loop (k) → performs multiplication and summation.
o Formula:
c[i][j]=∑k=0n−1a[i][k]⋅b[k][j]
7. Store the result
o Each computed value is stored in c[i][j].
8. Display the product matrix
o Print the elements of c row by row.
9. End the program.
PROGRAM 3:(character line and word counter)
AIM:
To write a Java program that counts the number of characters, words, and lines in a given
text entered by the user
ALGORITHM :
1. Start the program.
2. Initialize counters
o Set characterCount = 0
o Set wordCount = 0
o Set lineCount = 0
3. Prompt the user
o Display a message asking the user to enter text.
o Mention that typing "exit" will stop the input.
4. Read input lines in a loop
o Use a while(true) loop to continuously read lines from the user.
o For each line entered:
If the line equals "exit" (ignoring case), break the loop.
5. Update counters
o Add the length of the line to characterCount.
o Split the line into words using [Link]("\\s+") and add the number of
words to wordCount.
o Increment lineCount by 1.
6. Repeat until the user types "exit".
7. Display results
o Print the total number of characters.
o Print the total number of lines.
o Print the total number of words.
8. End the program.
PROGRAM 4:(Random Number Generator)
AIM:
To write a Java program that generates random numbers within a user-specified range (between a
minimum and maximum value).
ALGORITHM:
1. Start the program.
2. Create objects
o Create a Scanner object to read input from the user.
o Create a Random object to generate random numbers.
3. Input range values
o Ask the user to enter the maximum value (max).
o Ask the user to enter the minimum value (min).
4. Display message
o Print a message showing the range between min and max.
5. Generate random numbers
o Use the formula:
Random Number=[Link](max−min+1)+min
This ensures the random number lies between min and max (inclusive).
6. Print random numbers
o Generate and print three random numbers using the formula above.
7. End the program.
PROGRAM 5:(String Manipulation)
AIM:
To write a Java program that performs basic string manipulations such as:
Finding the length of a string
Accessing a character at a given index
Concatenating two strings
ALGORTHIM:
1. Start the program.
2. Input strings
o Prompt the user to enter the first string (str1).
o Prompt the user to enter the second string (str2).
3. Convert strings to character arrays
o Convert str1 into a character array arr1.
o Convert str2 into a character array arr2.
4. Display the first string
o Print the first string entered by the user.
5. Find string length
o Calculate the length of arr1 using [Link].
o Print the length of the first string.
6. Access character at given index
o Ask the user to enter an index position (pos).
o If pos is valid (between 0 and [Link] - 1), display the character at that
position.
o Otherwise, print “Invalid position”.
7. Concatenate two strings
o Create a new character array concat of size [Link] + [Link].
o Copy all characters of arr1 into concat.
o Copy all characters of arr2 into concat.
oConvert concat back into a string (result).
oPrint the concatenated string.
8. End the program.
PROGRAM 6:(String Operations)
AIM:
To write a Java program that demonstrates basic string operations using the String class, such
as:
Concatenation of two strings
Searching for a substring within a sentence
Extracting a substring from a given string
ALGORITHM:
Start the program.
Input two strings
Prompt the user to enter the first string (first).
Prompt the user to enter the second string (second).
Concatenate strings
Use the + operator to join first and second with a space in between.
Print the concatenated string.
Search for a substring
Ask the user to enter a sentence (sentence).
Ask the user to enter a word to search (searchWord).
Use the contains() method of the String class to check if sentence contains
searchWord.
If found, print a message saying the substring is present.
Otherwise, print a message saying the substring is not found.
Extract a substring
Ask the user to enter a string (text).
Ask the user to enter starting index (start) and ending index (end).
Use the substring(start, end) method to extract the portion of the string.
Print the extracted substring.
End the program.
PROGRAM 7:(String Buffer)
AIM:
To write a Java program that demonstrates string operations using the StringBuffer class,
such as:
Reversing a string
Finding the length of a string
Deleting a substring from a given string
ALGORITHM:
1. Start the program.
2. Input a string
o Prompt the user to enter a string.
o Store it in a StringBuffer object (str).
3. Reverse the string
o Use the reverse() method of StringBuffer to reverse the string.
o Print the reversed string.
4. Find length of reversed string
o Use the length() method of StringBuffer.
o Print the length of the reversed string.
5. Input a new string for deletion
o Prompt the user to enter another string.
o Store it in a new StringBuffer object (str).
6. Show length of new string
o Use length() method to display the length of the new string.
7. Perform deletion operation
o Ask the user to enter starting index (start) and ending index (end).
o Check if indices are valid:
start >= 0
end <= [Link]()
start < end
oIf valid, use delete(start, end) method to remove the substring.
oPrint the updated string and its new length.
oIf invalid, print “Invalid indices for deletion.”
8. End the program.
PROGRAM 8:(Random Numbers)
AIM:
To write a Java program that demonstrates multithreading, where two threads run
concurrently and print sequences of numbers independently.
ALGHORITHM:
1. Start the program.
2. Define first thread (Thread1)
o Create a class Thread1 that extends Thread.
o Override the run() method.
o Inside run(), use a loop to print numbers from 1 to 10.
o Use [Link](100) to pause execution for 100 milliseconds between prints.
o Handle InterruptedException using a try–catch block.
3. Define second thread (Thread2)
o Create a class Thread2 that extends Thread.
o Override the run() method.
o Inside run(), use a loop to print numbers from 90 to 100.
o Use [Link](100) to pause execution for 100 milliseconds between prints.
o Handle InterruptedException using a try–catch block.
4. Create main class (Write)
o In the main() method, create objects of Thread1 and Thread2.
o Start both threads using the start() method.
5. Concurrent execution
o When start() is called, both threads begin execution concurrently.
o Thread1 prints numbers from 1 to 10.
o Thread2 prints numbers from 90 to 100.
o The outputs may appear interleaved because threads run independently.
6. End the program.
PROGRAM 9:(Exceptions)
AIM:
To write a Java program that demonstrates exception handling by catching different types of
runtime errors such as:
ArithmeticException
NumberFormatException
ArrayIndexOutOfBoundsException
NegativeArraySizeException
ALGORITHM:
1. Start the program.
2. ArithmeticException demonstration
o Try dividing a number by zero (10 / 0).
o Since division by zero is not allowed, an ArithmeticException occurs.
o Catch the exception and print a message.
3. NumberFormatException demonstration
o Try converting a non-numeric string (e.g., "abc") into an integer using
[Link]().
o Since the string is invalid, a NumberFormatException occurs.
o Catch the exception and print a message.
4. ArrayIndexOutOfBoundsException demonstration
o Create an array with three elements.
o Try accessing an invalid index (e.g., arr[5]).
o Since the index is out of bounds, an ArrayIndexOutOfBoundsException occurs.
o Catch the exception and print a message.
5. NegativeArraySizeException demonstration
o Try creating an array with a negative size (e.g., new int[-5]).
o Since array size cannot be negative, a NegativeArraySizeException occurs.
o Catch the exception and print a message.
6. End the program.
PROGRAM 10:(File Information)
AIM:
To write a Java program that checks and displays information about a file, such as whether it
exists, its readability, writability, type, and size.
ALGORITHM:
Start the program.
Create Scanner object
Use Scanner to read input from the user.
Prompt the user for file name
Ask the user to enter the file name.
If the file is not in the current directory, the user should provide the full path.
Create File object
Use File file = new File(fileName); to create a File object representing the given
file.
Check if file exists
Use [Link]() method.
If the file exists, print “File exists: Yes”.
Otherwise, print “File exists: No” and skip further checks.
Check readability
Use [Link]() method.
Print whether the file is readable (true/false).
Check writability
Use [Link]() method.
Print whether the file is writable (true/false).
Check type of file
Use [Link]() method.
If true, print “Directory”.
Otherwise, print “File”.
Check file length
Use [Link]() method.
Print the size of the file in bytes.
Close Scanner
Close the Scanner object to free resources.
End the program.
PROGRAM 11:(Text Editor With Font Controls)
AIM:
To write a Java program using Swing that creates a simple text editor with controls to change
the font type, size, and style (bold/italic) of the text entered in a text area.
ALGORITHM:
1. Start the program.
2. Create a class extending JFrame
o Define a class TextEditor that extends JFrame.
o This will serve as the main window (frame) of the application.
3. Initialize components
o Create a JTextArea for entering and displaying text.
o Add a JScrollPane to allow scrolling inside the text area.
o Create a JPanel to hold control components (font, size, style, apply button).
4. Add font selection control
o Create a JComboBox<String> with font options (e.g., Arial, Helvetica, Times
New Roman, Courier).
o Set a default font (e.g., Arial).
5. Add font size selection control
o Create another JComboBox<String> with size options (e.g., 8, 10, 12, 14, 16, 18,
20, 22, 24).
o Set a default size (e.g., 16).
6. Add style controls
o Create a JCheckBox for Bold.
o Create another JCheckBox for Italic.
7. Add Apply button
o Create a JButton labeled “Apply”.
o Add an ActionListener to the button.
o When clicked, it calls the method applyFontSettings().
8. Define applyFontSettings() method
o Get the selected font from fontComboBox.
o Get the selected size from sizeComboBox.
o Determine style based on checkboxes:
If both Bold and Italic are selected → [Link] | [Link].
If only Bold is selected → [Link].
If only Italic is selected → [Link].
Otherwise → [Link].
o Create a new Font object with these settings.
o Apply the font to the textArea.
9. Add components to frame
o Add the control panel at the top (NORTH) of the frame.
o Add the scrollable text area at the center of the frame.
10. Set frame properties
o Set title, size, and default close operation.
o Center the frame on the screen using setLocationRelativeTo(null).
11. Run the program
o In the main() method, use [Link]() to create and
display the frame.
12. End the program.
PROGRAM 12:(Mouse Event Example)
AIM:
To write a Java program that demonstrates handling of mouse events (click, press, release,
enter, exit, drag, move) using AWT event handling and displays the event name on the window.
ALGORITHM:
1. Start the program.
2. Create a class extending Frame
o Define a class MouseEventExample that extends Frame.
o This will serve as the main application window.
3. Initialize event name variable
o Create a string variable eventName to store the current mouse event name.
4. Set up the frame
o Set the title of the frame.
o Set the size of the frame.
o Make the frame visible.
5. Add mouse event listeners
o Use addMouseListener() with a MouseAdapter to handle:
mouseClicked → set eventName = "Mouse Clicked"
mousePressed → set eventName = "Mouse Pressed"
mouseReleased → set eventName = "Mouse Released"
mouseEntered → set eventName = "Mouse Entered"
mouseExited → set eventName = "Mouse Exited"
o Call repaint() after each event to refresh the display.
6. Add mouse motion listeners
o Use addMouseMotionListener() with a MouseAdapter to handle:
mouseDragged → set eventName = "Mouse Dragged"
mouseMoved → set eventName = "Mouse Moved"
o Call repaint() after each event.
7. Add window closing event
o Use addWindowListener() with a WindowAdapter.
o In windowClosing(), call [Link](0) to close the program.
8. Override paint() method
o Use the paint(Graphics g) method to display the current event name.
o Set font style and size.
o Set text color.
o Calculate coordinates to center the text using FontMetrics.
o Draw the string on the frame.
9. Main method
o In main(), create an object of MouseEventExample.
o Display the frame.
10. End the program.
PROGRAM 13:(My Calculator)
AIM:
To write a Java program using AWT that creates a simple calculator capable of performing
basic arithmetic operations (addition, subtraction, multiplication, division) on two numbers
entered by the user.
ALGORITHM:
Start the program.
Create a class extending Frame
Define a class MyCalculator that extends Frame and implements ActionListener.
This allows the program to create a GUI window and handle button click events.
Declare components
Labels (lbl1, lbl2, lbl3) for Number 1, Number 2, and Result.
TextFields (tf1, tf2, tf3) for input and output.
Buttons (btn1, btn2, btn3, btn4) for operations (+, −, ×, ÷).
Initialize components
Set positions and sizes of labels, text fields, and buttons using setBounds().
Add all components to the frame using add().
Register event listeners
Attach ActionListener to each button (btn1, btn2, btn3, btn4).
This ensures that when a button is clicked, the actionPerformed() method is executed.
Set frame properties
Set frame size using setSize().
Use setLayout(null) for absolute positioning.
Set title of the frame.
Make the frame visible using setVisible(true).
Handle button clicks (actionPerformed method)
Read values from tf1 and tf2 using getText() and convert them to double.
Check which button was clicked using [Link]().
Perform the corresponding operation:
o If btn1 → Addition (num1 + num2).
o If btn2 → Subtraction (num1 - num2).
o If btn3 → Multiplication (num1 * num2).
o If btn4 → Division (num1 / num2).
Display the result in tf3 using setText().
Main method
Create an object of MyCalculator to run the program.
End the program.
PROGRAM 14:(Traffic Lights)
AIM:
To write a Java program using Swing that simulates a traffic light system. The program
allows the user to select a light (Red, Orange, Green) using radio buttons and displays the
corresponding action message (“STOP”, “READY”, “GO”) with appropriate colors.
ALGORITHM:
1. Start the program.
2. Create a class extending JFrame
o Define a class TrafficLights that extends JFrame and implements
ActionListener.
o This allows the program to create a GUI window and respond to user actions.
3. Declare components
o JLabel lbl1 → to display the traffic light message (“STOP”, “READY”, “GO”).
o JLabel lbl2 → to display the instruction “Select Lights”.
o JRadioButton rl, ol, gl → radio buttons for Red, Orange, and Green lights.
o ButtonGroup bg → to group the radio buttons so only one can be selected at a
time.
4. Initialize components
o Set fonts and positions using setFont() and setBounds().
o Add labels and radio buttons to the frame using add().
o Set background colors for each radio button (Red, Orange, Green).
5. Add ActionListeners
o Attach ActionListener to each radio button (rl, ol, gl).
o This ensures that when a radio button is selected, the actionPerformed()
method is executed.
6. Group radio buttons
o Use ButtonGroup to group the three radio buttons so only one can be active at a
time.
7. Set frame properties
o Set title using setTitle().
o Set size using setSize().
o Use setLayout(null) for absolute positioning.
o Make the frame visible using setVisible(true).
8. Handle events (actionPerformed method)
o If Red Light (rl) is selected → set lbl1 text to “STOP” and color to Red.
o If Orange Light (ol) is selected → set lbl1 text to “READY” and color to
Orange.
o If Green Light (gl) is selected → set lbl1 text to “GO” and color to Green.
9. Main method
o In main(), create an object of TrafficLights to run the program.
10. End the program.