Java Lab Program COPY2
Java Lab Program COPY2
Write a Java program that prompts the user for an integer and then
prints out all the prime numbers up to that Integer
Algorithm:
1. Start.
2. Initialize variables i, j, n, s = 0.
3. Read input n from the user.
4. Print headers for prime numbers.
5. Loop i from 2 to n.
6. Set s = 0.
7. Loop j from 2 to i/2.
8. If i % j == 0, set s = 1 and break.
9. If s == 0, print i.
10. End.
Source Code:
import java.io.*;
class prime
{
public static void main(String args[])
{
try
{
InputStreamReader n1 = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(n1);
int i,j,n, s =0;
System.out.println( "PRIME NUMBER");
System.out.print( "GIVEN NUMBER IS =");
n = Integer.parseInt(br.readLine());
System.out.println ("PRIME NUMBERS:");
for (i = 2; i <= n; i++)
{
s = 0;
for (j = 2; j <= i/2; j++)
{
if (i % j == 0)
{
s++;
break;
}
}
if (s == 0)
System.out.println (i);
}
}catch(Exception e){}
}
}
OUTPUT:
Algorithm
1. Start
2. Accept two matrices, A and B, as input.
3. Check if the number of columns in matrix A is equal to the number of
rows in matrix B:
4. If not equal, print an error message indicating that the matrices cannot
be multiplied.
5. If equal, continue to the next step.
6. Create an empty result matrix, C, with dimensions (number of rows in A)
x (number of columns in B).
7. Iterate through each row i of matrix A:
8. Iterate through each column j of matrix B:
9. Initialize the element c_ij of matrix C to 0.
10. Iterate through each element k of row i of matrix A and column j of
matrix B:
11. Multiply the corresponding elements from matrices A and B: A[i][k] *
B[k][j].
12. Add the result to c_ij.
13. Repeat step 5 for all elements of matrix C.
14. Print matrix C, which is the result of multiplying matrices A and B.
15. End
Source Code:
public class Matmul
{
public static void main(String args[])
{
int a[][]={{1,1,1},{2,2,2},{3,3,3}};
int b[][]={{1,1,1},{2,2,2},{3,3,3}};
int c[][]=new int[3][3];
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
c[i][j]=0;
for(int k=0;k<3;k++)
{
c[i][j]+=a[i][k]*b[k][j];
}
System.out.print(c[i][j]+" ");
}//end of j loop
System.out.println();//new line
}
}
}
OUTPUT:
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output:
3. Java program that displays the number of characters, lines and words in
a text
Algorithm:
1. Start.
2. Initialize cc = 0, wc = 0, lc = 0.
3. Create BufferedReader to read input.
4. Print message to enter text (stop at "END").
5. Loop to read lines from input.
6. If line is "END", break the loop.
7. Increment lc (line count).
8. Add line length to cc (character count).
9. Use StringTokenizer to count words and add to wc.
10. Print line, word, and character counts.
11. End.
Source Code:
import java.io.*;
import java.util.StringTokenizer;
lc++;
cc += line.length();
Algorithm:
1. Start
2. Define the lower and upper limits for generating random numbers.
3. Create an instance of the Random class.
4. Generate a random number between the lower and upper limits using
the nextInt() method of the Random class.
5. Print the generated random number.
6. Check the generated random number:
7. If the random number is less than 20:
8. Print a message indicating that the generated number is less than 20.
9. If the random number is between 20 and 29:
10. Print a message indicating that the generated number is between 20 and
29.
11. If the random number is 30 or greater:
12. Print a message indicating that the generated number is 30 or greater.
13. End
Source Code:
import java.util.Random;
public class RandomNumberGenerator4 { public static void main(String[] args) {
// Define the lower and upper limits int lowerLimit = 10;
int upperLimit = 50;
// Create an instance of the Random class Random random = new Random();
// Generate a random number between the lower and upper limits
int randomNumber = random.nextInt(upperLimit - lowerLimit + 1) + lowerLimit;
// Print the generated random number
System.out.println("Generated Random Number: " + randomNumber);
// Print message according to the range of the generated number if
(randomNumber < 20) {
System.out.println("Generated number is less than 20");
} else if (randomNumber >= 20 && randomNumber < 30) {
System.out.println("Generated number is between 20 and 29");
} else {
System.out.println("Generated number is 30 or greater");
}
}
}
OUTPUT:
Algorithm:
1. Start
2. Create BufferedReader for input.
3. Prompt and read str1 (first string).
4. Prompt and read str2 (second string).
5. Print the length of str1.
6. Print the length of str2.
7. Prompt for a position to find a character in str1.
8. Read and convert position input to integer.
9. If position is valid, print the character at that position.
10. If position is invalid, print an error message.
11. Concatenate str1 and str2 and print the result.
12. End.
Source Code
Import java.io.*;
public class strmanip {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
OUTPUT:
6. Java program to perform the following string operations using String
class: String Concatenation, Search String and Extract String
Algorithm:
1. Start
2. Create a Scanner object for input.
3. Prompt and read str1 (first string).
4. Prompt and read str2 (second string).
5. Concatenate str1 and str2, then print the result.
6. Prompt and read mainString (string for substring search).
7. Prompt and read subString (substring to search).
8. Check if subString is present in mainString and print the result.
9. Prompt and read originalString (string for index-based extraction).
10. Prompt and read startIndex.
11. Prompt and read endIndex.
12. Extract substring from originalString using indices and print the result.
13. Close the Scanner.
14. End.
Source Code:
import java.util.Scanner;
public class UserStringOperations { public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking input strings from the user System.out.println("Enter the first
string:"); String str1 = scanner.nextLine(); System.out.println("Enter the second
string:"); String str2 = scanner.nextLine();
// String Concatenation
String concatenatedString = str1.concat(str2);
System.out.println("Concatenated String: " + concatenatedString);
// Search a substring System.out.println("Enter a new string:"); String
mainString = scanner.nextLine();
System.out.println("Enter the substring to search:"); String subString =
scanner.nextLine();
boolean isSubstringPresent = mainString.contains(subString); if
(isSubstringPresent) {
System.out.println("Substring '" + subString + "' found in the main string.");
} else {
System.out.println("Substring '" + subString + "' not found in the main string.");
}
// To extract substring from given string
System.out.println("Enter the main string to be searched according to index
positions:"); String originalString = scanner.nextLine();
System.out.println("Enter the start index:"); int startIndex = scanner.nextInt();
System.out.println("Enter the end index:");
int endIndex = scanner.nextInt();
String extractedSubstring = originalString.substring(startIndex, endIndex);
System.out.println("Extracted Substring: " + extractedSubstring);
scanner.close();
}
}
OUTPUT:
Algorithm:
1. Start
2. Create BufferedReader for input.
3. Prompt and read input string.
4. Create StringBuffer object sb with input.
5. Calculate and print the length of the string.
6. Reverse and print the string.
7. Reverse back to restore the original string.
8. Prompt and read startIndex for deletion.
9. Prompt and read endIndex for deletion.
10. If indices are valid, delete the substring and print the modified string.
11. If indices are invalid, print an error message.
12. End.
Source code:
import java.io.*;
public class strbufopn {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
// Input the string
System.out.print("Enter a string: ");
String input = br.readLine();
StringBuffer sb = new StringBuffer(input);
// a) Length of the string
int length = sb.length();
System.out.println("Length of the string: " + length);
// b) Reverse the string
System.out.println("Reversed string: " + sb.reverse());
sb.reverse(); // Revert back to the original string
// c) Delete a substring from the string
System.out.print("Enter the start index of the substring to delete: ");
int startIndex = Integer.parseInt(br.readLine());
System.out.print("Enter the end index of the substring to delete: ");
int endIndex = Integer.parseInt(br.readLine());
if (startIndex >= 0 && endIndex <= sb.length() && startIndex < endIndex) {
sb.delete(startIndex, endIndex);
System.out.println("String after deletion: " + sb);
} else {
System.out.println("Invalid indices for deletion!");
}
}
}
8. Java program that implements a multi-thread application to generate
random integer, square of even numbers and cube of odd numbers
Algorithm:
1. Start
2. Create RandomNumberGenerator class implementing Runnable.
3. Inside run() method:
4. Create Random object.
5. Enter an infinite loop:
6. Sleep for 1 second.
7. Generate a random number (0-99).
8. Print the generated number.
9. If the number is even, call SquareThread.square().
10. If the number is odd, call CubeThread.cube().
11. Create SquareThread class with square() method to print the square of a
number.
12. Create CubeThread class with cube() method to print the cube of a
number.
13. In MultiThreadApplication class:
14. Create a thread for RandomNumberGenerator.
15. Start the thread.
16. End.
Source Code:
import java.util.Random;
class RandomNumberGenerator implements Runnable
{ @Override
public void run() {
Random random = new Random(); while (true) {
try {
Thread.sleep(1000);
int randomNumber = random.nextInt(100); System.out.println("Generated
Number: " + randomNumber); if (randomNumber % 2 == 0) {
SquareThread.square(randomNumber);
} else {
CubeThread.cube(randomNumber);
}
} catch (InterruptedException e) { e.printStackTrace();
}
}
}
}
class SquareThread {
public static void square(int number) { System.out.println("Square: " + (number
* number));
}
}
class CubeThread {
public static void cube(int number) {
System.out.println("Cube: " + (number * number * number));
}
}
public class MultiThreadApplication { public static void main(String[] args) {
Thread generatorThread = new Thread(new RandomNumberGenerator());
generatorThread.start();
}
}
OUTPUT:
Algorithm:
1. Start
2. Define NumberPrinter class implementing Runnable.
3. Create NumberPrinter constructor with start and end values.
4. Implement run() method to print numbers from start to end.
5. In Main class, create NumberPrinter instance printer1 for range 1-10.
6. Create NumberPrinter instance printer2 for range 90-100.
7. Create Thread1 with printer1.
8. Create Thread2 with printer2.
9. Start Thread1.
10. Start Thread2.
11. End.
Source Code:
class NumberPrinter implements Runnable { private final int start;
private final int end;
public NumberPrinter(int start, int end) { this.start = start;
this.end = end;
}
@Override
public void run() {
for (int i = start; i <= end; i++) {
System.out.println(Thread.currentThread().getName() + ": " + i);
}
}
}
public class Main {
public static void main(String[] args) {
// Create instances of the NumberPrinter for Thread1 and Thread2
NumberPrinter printer1 = new NumberPrinter(1, 10); NumberPrinter printer2 =
new NumberPrinter(90, 100);
// Create threads for Thread1 and Thread2
Thread thread1 = new Thread(printer1, "Thread1"); Thread thread2 = new
Thread(printer2, "Thread2");
// Start the threads thread1.start(); thread2.start();
}}
OUTPUT
Algorithm:
1. Start
2. Handle Arithmetic Exception:
o Try to divide a number by zero.
o If an exception occurs, catch it and display
"ArithmeticException: Cannot divide by zero."
3. Handle Number Format Exception:
o Try to convert an invalid string ("ABC") to an integer.
o If an exception occurs, catch it and display
"NumberFormatException: Invalid number
format."
4. Handle Array Index Out of Bounds Exception:
o Declare an integer array with some elements.
o Try to access an invalid index (out of array bounds).
o If an exception occurs, catch it and display
"ArrayIndexOutOfBoundsException: Index out of
range."
5. Handle Negative Array Size Exception:
o Try to create an array with a negative size.
o If an exception occurs, catch it and display
"NegativeArraySizeException: Array size
cannot be negative."
6. End
Source Code
public class ExceptionDemo {
public static void main(String[] args) {
// 1. ArithmeticException
try {
int result = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: Cannot divide by zero.");
}
// 2. NumberFormatException
try {
int num = Integer.parseInt("ABC"); // Invalid number conversion
} catch (NumberFormatException e) {
System.out.println("NumberFormatException: Invalid number format.");
}
// 3. ArrayIndexOutOfBoundsException
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // Accessing out of bounds index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException: Index out of
range.");
}
// 4. NegativeArraySizeException
try {
int[] arr = new int[-5]; // Negative size array
} catch (NegativeArraySizeException e) {
System.out.println("NegativeArraySizeException: Array size cannot be
negative.");
}
}
}
OUTPUT:
ArithmeticException: Cannot divide by zero.
NumberFormatException: Invalid number format.
ArrayIndexOutOfBoundsException: Index out of range.
NegativeArraySizeException: Array size cannot be negative.
11. Wite a Java program that reads on file name from the user, then displays
information whether the file exists, is readable, is writable, the type of file
and the length of the file in bytes.
Algorithm :
1. Start
2. Print "Please enter the file name:"
3. Read inputFileName from the user
4. Check if the file exists:
5. If file exists:
6. Print "File exists." Check file permissions:
7. Check if the file is readable:
8. If true, Print "File is readable." Else, Print "File is not readable."
9. Check if the file is writable:
10. if true, Print "File is writable." Else, Print "File is not writable."
11. Get the type of the file:
12. Use system functions to determine the file type
13. Print the file type
14. Get the length of the file:
15. Use system functions to get the length of the file
16. Print the length of the file in bytes
17. If file doesn't exist:
18. Print "File does not exist."
19. End
Source Code:
import java.io.File; import java.util.Scanner; public class FileInfo {
public static void main(String[] args) { Scanner scanner = new
Scanner(System.in);
// Prompt user to enter the file name System.out.println("Enter the file
name:"); String fileName = scanner.nextLine();
// Create a File object with the given file name File file = new File(fileName);
// Check if the file exists if (file.exists()) {
System.out.println("File exists: Yes");
OUTPUT:
Algorithm:
1. Initialize Frame
o Create a JFrame with title, size, and close operation.
2. Create Components
o JTextArea for text input.
Algorithm
1. Initialize Frame
o Create a Frame and set title, size, and visibility.
2. Implement Mouse Listener
o Use MouseAdapter to override mouse event methods:
Algorithm
1. Initialize Frame
o Create a JFrame with title, layout, and close operation.
o Add a JTextField for displaying input/output (non-editable).
2. Create Buttons
o Create digit buttons (0-9) and add action listeners.
o Create operator buttons (+, -, *, /, %, =) and add action listeners.
o Arrange buttons in a JPanel using GridLayout.
3. Handle Button Clicks (actionPerformed)
o If a digit is clicked, update currentInput and display it.
o If an operator (+, -, *, /, %) is clicked:
Perform the previous calculation (if applicable).
Store the operator for the next calculation.
Set isNewInput to true for new entry.
o If = is clicked, perform the calculation and display the result.
4. Perform Calculations (calculate)
o Convert currentInput to a number.
o Perform the operation based on operator.
o Handle division by zero error.
o Update the display with the result.
5. Reset Calculator (reset)
o Set currentInput to an empty string.
o Initialize result to 0 and operator to a space.
o Set textField display to "0".
6. Run Program
o Create an instance of SimpleCalculator in main().
Source Code:
import java.awt.*;
import java.awt.event.*; i
mport javax.swing.*;
public class SimpleCalculator extends JFrame implements ActionListener {
private JTextField textField;
private JButton[] digitButtons;
private JButton addButton, subtractButton, multiplyButton, divideButton,
modulusButton, equalsButton;
private String currentInput; private double result; private char operator; private
boolean isNewInput; public SimpleCalculator() {
setTitle("Simple Calculator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new
BorderLayout());
textField = new JTextField(); textField.setEditable(false); add(textField,
BorderLayout.NORTH);
Algorithm:
1. Initialize Frame
o Create a JFrame with a title, layout, and close operation.
2. Create Radio Buttons
o Create three JRadioButtons for "Red", "Yellow", and "Green".
SwingUtilities.invokeLater().
Source Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TrafficLightSimulator extends JFrame implements ActionListener {
private JRadioButton redButton, yellowButton, greenButton;
private ButtonGroup buttonGroup; private JLabel messageLabel; public
TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new
BorderLayout());
redButton = new JRadioButton("Red"); yellowButton = new
JRadioButton("Yellow"); greenButton = new JRadioButton("Green");
redButton.addActionListener(this); yellowButton.addActionListener(this);
greenButton.addActionListener(this); JPanel radioPanel = new JPanel();
radioPanel.add(redButton); radioPanel.add(yellowButton);
radioPanel.add(greenButton); add(radioPanel, BorderLayout.CENTER);
messageLabel = new JLabel();
messageLabel.setHorizontalAlignment(SwingConstants.CENTER);
messageLabel.setFont(new Font("Arial", Font.BOLD, 18)); add(messageLabel,
BorderLayout.NORTH);
pack(); setLocationRelativeTo(null); setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) { String message = "";
Color color = Color.BLACK;
if (e.getSource() == redButton) { message = " Stop";
color = Color.RED;
} else if (e.getSource() == yellowButton) { message = "Ready";
color = Color.YELLOW;
} else if (e.getSource() == greenButton) { message = "Go";
color = Color.GREEN;
}
messageLabel.setText(message); messageLabel.setForeground(color);
}
public static void main(String[] args) { SwingUtilities.invokeLater(new
Runnable() {
public void run() {
new TrafficLightSimulator();
}
});
}
}
OUTPUT: