Java Programs 2025 Ii BSC CS
Java Programs 2025 Ii BSC CS
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+" ");
}
}
}
}
OUTPUT :
RESULT :
Thus the above Program was successfully executed and the output was
verified.
AIM :
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 :
}
System.out.println();
}
}
}
OUTPUT :
RESULT:
AIM :
To develop a Java program that displays the number of characters,
lines and words in a text.
ALGORITHM :
PROGRAM CODE :
OUTPUT :
RESULT :
AIM :
ALGORITHM :
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.");
}
else {
System.out.println("The number is greater than 35.");
}
}
}
OUTPUT :
RESULT:
Thus the above Java program for generate Random numbers was
executed Successfully.
AIM :
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 :
OUTPUT :
RESULT :
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 :
OUTPUT :
RESULT :
Thus the Java programming used to perform String Operations was
executed successfully.
AIM :
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 :
OUTPUT :
RESULT :
AIM :
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 :
}
public class MultiThread {
public static void main(String[] args) {
Thread1 t1 = new Thread1();
Thread2 t2 = new Thread2();
t1.start();
} t2.start();
}
OUTPUT :
RESULT :
Thus the Java program used to implement Multi thread was executed
successfully.
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());
}
try {
int[] array = new int[-5];
} catch (NegativeArraySizeException e) {
System.out.println("Caught NegativeArraySizeException: " + e.getMessage());
}
}
}
OUTPUT :
RESULT :
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());
OUTPUT :
RESULT :
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 :
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) {
new MouseEventDemo();
}
}
OUTPUT :
RESULT :
Thus the Java programming to handle all Mouse Events was
executed successfully.
AIM :
To develop a Java program that works as a simple calculator.
ALGORITHM :
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");
OUTPUT :
RESULT :
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.
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);
}
});
OUTPUT :
RESULT :
Thus the Java programming to implement the Traffic Light
concept was executed Successfully.
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 :
PROGRAM CODE :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
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");
// Size selection
String[] sizes = {"16", "20", "24", "28", "32"};
sizeBox = new JComboBox<>(sizes);
sizeBox.setSelectedItem("20");
// Show frame
frame.setVisible(true);
}
}
}
OUTPUT :
RESULT :
Thus the Java programming was used to implement the Text
Editor was executed successfully.