II Cs Java Programming
II Cs Java Programming
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.
PROCEDURE
Step 1: Import the Scanner Class The program starts by importing the
`java.util.Scanner` class, which allows the program to read input from the user.
Step 2: Create a Scanner Object A `Scanner` object named `scanner` is created to
read the user's input.
Step 3: Prompt the User for Input.
Step 4: Read the User's Input the user's input is read using `int number =
scanner.nextInt()` and stored in the `number` variable.
Step 5: The program prints the prime numbers up to the input number using a `for`
loop.
Step 6: The `isPrime` method checks if a number is prime by iterating from 2 to
the square root of the number and checking for divisibility.
Step 7: Print the Prime Number
Step 8: The program repeats steps 5-7 until all prime numbers up to the input
number have been printed.
1. Prime.java
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter an integer: ");
int number = scanner.nextInt();
System.out.println("Prime numbers up to " + number + ":");
for (int i = 2; i <= number; i++) {
if (isPrime(i)) {
System.out.print(i + " ");
}
}
}
public static boolean isPrime(int num) {
if (num < 2) return false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
OUTPUT
AIM
To Write a Java program to multiply two given matrices.
PROCEDURE
Step 1: The program starts by importing the `java.util.Scanner` class.
Step 3: The program prompts the user to enter the number of rows and
columns for the first and second matrices.
Step 4: The user's input is read using `scanner.nextInt()` and stored in the
`rows1`, `cols1`, `rows2`, and `cols2 variables.
Step 5: The program checks if the number of columns in the first matrix is
equal to the number of rows in the second matrix. If not, it prints an error message
and exits.
2.Matrix.java
import java.util.Scanner;
if (cols1 != rows2) {
System.out.println("Matrix multiplication is not possible.");
return;
}
System.out.println("Resultant Matrix:");
for (int[] row : result) {
for (int val : row) {
System.out.print(val + " ");
}
System.out.println();
}
scanner.close();
}
}
AIM
Write a Java program that displays the number of characters, lines and
Words in a text
PROCEDURE
Step 7: Print the text statistics, including lines, words, and characters.
3. Text.java
import java.util.Scanner;
public class Text {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int characterCount = 0;
int wordCount = 0;
int lineCount = 0;
while (true) {
String line = scanner.nextLine();
if (line.isEmpty()) {
break;
}
lineCount++;
characterCount += line.replace(" ", "").length();
wordCount += line.trim().split("\\s+").length;
}
System.out.println("\nText Statistics:");
System.out.println("Number of lines: " + lineCount);
System.out.println("Number of words: " + wordCount);
System.out.println("Number of characters (excluding spaces): " +
characterCount);
scanner.close();
}
}
AIM
Generate random numbers between two given limits using Random class
and print messages according to the range of the value generated.
PROCEDURE
Step 1: Import Necessary Classes
Step 2: Create a `Scanner` object to read user input.
scanner.close();
}
}
AIM
To Write a program to do String Manipulation using CharacterArray and
perform the following string operations:
a. String length
b. Finding a character at a particular position
c. Concatenating two strings
PROCEDURE
1. Import `java.util.Scanner` class.
2. Create a `Scanner` object to read user input.
3. Prompt user to enter the first string.
4. Convert the string to a character array and find its length.
5. Prompt user to enter a position to find a character.
6. Check if the position is valid and print the character at that position.
7. Prompt user to enter the second string.
8. Concatenate the two strings using character arrays.
9. Print the concatenated string.
10. Close the `Scanner` object.
5.StrManipulation.java
import java.util.Scanner;
public class StrManipulation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.close();
}
}
AIM
Write a program to perform the following string operations using String
class:
a. String Concatenation
b. Search a substring
c. To extract substring from given string
PROCEDURE
1. Import `java.util.Scanner` class.
2. Create a `Scanner` object to read user input.
3. Prompt user to enter two strings.
4. Concatenate the two strings.
5. Print the concatenated string.
6. Prompt user to enter a substring to search for.
7. Check if the first string contains the substring.
8. Print the result of the substring search.
9. Prompt user to enter start and end indices to extract a substring.
10. Extract the substring using the provided indices.
11. Print the extracted substring or an error message if indices are invalid.
12. Close the `Scanner` object.
6. StrOperation.java
import java.util.Scanner;
scanner.close();
}
}
AIM
Write a program to perform string operations using String Buffer class:
a. Length of a string
b. Reverse a string
c. Delete a substring from the given string
PROCEDURE
1. Import `java.util.Scanner` class.
2. Create a `Scanner` object to read user input.
3. Prompt user to enter a string.
4. Create a `StringBuffer` object with the input string.
5. Calculate and print the length of the string.
6. Reverse the string using `reverse()` method.
7. Print the reversed string.
8. Prompt user to enter start and end indices to delete a substring.
9. Delete the substring using `delete()` method.
10. Print the string after deletion or an error message if indices are invalid.
11. Close the `Scanner` object.
7.StrBuffer.java
import java.util.Scanner;
public class StrBuffer {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
AIM
Write a java program that implements a multi-thread application that has
three threads. First thread generates random integer every 1 second and if the value
is even, second thread computes the square of the number and prints. If the value is
odd, the third thread will print the value of cube of the number.
PROCEDURE
1. Create a `RandomNumberGenerator` class that extends `Thread`.
2. Create a `NumberProcessor` class that extends `Thread`.
3. Initialize `NumberProcessor` objects for even and odd numbers.
4. Initialize a `RandomNumberGenerator` object with the even and odd
processors.
5. Start the even, odd, and random number generator threads.
6. In the `RandomNumberGenerator` thread.
7. In the `NumberProcessor` thread , Print the result.
8.ThreadApp.java
import java.util.Random;
if (number % 2 == 0) {
evenProcessor.process(number);
} else {
oddProcessor.process(number);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
if ("Even".equals(type)) {
System.out.println("Square of " + number + ": " + (number *
number));
} else {
System.out.println("Cube of " + number + ": " + (number *
number * number));
}
}
}
}
}
evenProcessor.start();
oddProcessor.start();
randomNumberGenerator.start();
}
}
AIM
Write a threading program which uses the same method asynchronously to
print the numbers 1to10 using Thread1 and to print 90 to100 using Thread2.
PROCEDURE
1. Create a `NumberPrinter` class that implements `Runnable`.
2. Initialize `NumberPrinter` objects with start and end numbers.
3. Create `Thread` objects with the `NumberPrinter` objects.
4. Start the threads.
5. In the `NumberPrinter` class:
- Print numbers from start to end with a 500ms delay.
- Use `Thread.currentThread().getName()` to print the thread name.
9.Threads.java
class NumberPrinter implements Runnable {
private final int start;
private final int end;
thread1.start();
thread2.start();
}
}
AIM
Write a program to demonstrate the use of following exceptions.
a. Arithmetic Exception
b. Number Format Exception
c. ArrayIndexOutofBoundException
d. NegativeArraySizeException
PROCEDURE
1. Create a `try` block to enclose code that may throw an exception.
2. Attempt to perform operations that may throw exceptions, such as:
- Division by zero (ArithmeticException)
- Parsing a non-numeric string to an integer (NumberFormatException)
- Accessing an array index out of bounds
(ArrayIndexOutOfBoundsException)
- Creating an array with a negative size (NegativeArraySizeException)
3. Create a corresponding `catch` block for each type of exception.
4. Handle the exception by printing an error message or taking alternative
action.
5. Repeat steps 1-4 for each type of exception.
10.Exception.java
public class Exception {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " +
e.getMessage());
}
try {
int number = Integer.parseInt("ABC");
} catch (NumberFormatException e) {
System.out.println("NumberFormatException caught: " +
e.getMessage());
}
try {
int[] array = {1, 2, 3};
int value = array[5];
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException caught: " +
e.getMessage());
}
try {
int[] negativeArray = new int[-5];
} catch (NegativeArraySizeException e) {
System.out.println("NegativeArraySizeException caught: " +
e.getMessage());
}
}
}
AIM
Write 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
PROCEDURE
11.FileInformation.java
import java.io.File;
import java.util.Scanner;
if (file.exists()) {
System.out.println("File exists: Yes");
System.out.println("Readable: " + (file.canRead() ? "Yes" : "No"));
System.out.println("Writable: " + (file.canWrite() ? "Yes" : "No"));
if (file.isDirectory()) {
System.out.println("File type: Directory");
} else if (file.isFile()) {
System.out.println("File type: Regular file");
} else {
System.out.println("File type: Unknown");
}
scanner.close();
}
}
AIM
Write a program to accept a text and change its size and font. Include bold
italic options. Use frames and controls.
PROCEDURE
1. Create a JFrame with a FlowLayout.
2. Add input field and label for user to enter text.
3. Add label to display styled text.
4. Add combo boxes for font and size selection.
5. Add radio buttons for style selection (plain, bold, italic).
6. Add apply button to apply selected style.
7. Implement ActionListener for apply button:
- Get input text, selected font, size, and style.
- Set styled text to display label.
- Update display label’s font and style.
8. Make frame visible using SwingUtilities.invokeLater.
12.TextStyleChanger.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public TextStyleChanger() {
setTitle("Text Style Changer");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
if (boldButton.isSelected()) {
fontStyle = Font.BOLD;
} else if (italicButton.isSelected()) {
fontStyle = Font.ITALIC;
}
displayLabel.setText(text);
displayLabel.setFont(new Font(fontName, fontStyle, fontSize));
}
AIM
Write 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).
PROCEDURE
1. Create a JFrame with a BorderLayout.
2. Add a JLabel to display mouse events.
3. Implement MouseListener for mouse events:
- mouseClicked: update label text to "Mouse Clicked".
- mousePressed: update label text to "Mouse Pressed".
- mouseReleased: update label text to "Mouse Released".
- mouseEntered: update label text to "Mouse Entered".
- mouseExited: update label text to "Mouse Exited".
4. Implement MouseMotionListener for mouse motion events:
- mouseMoved: update label text to "Mouse Moved".
- mouseDragged: update label text to "Mouse Dragged".
5. Make frame visible using SwingUtilities.invokeLater.
13.MouseEventDemo.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public MouseEventDemo() {
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
eventLabel.setText("Mouse Clicked");
}
public void mousePressed(MouseEvent e) {
eventLabel.setText("Mouse Pressed");
}
addMouseMotionListener(new MouseAdapter() {
public void mouseMoved(MouseEvent e) {
eventLabel.setText("Mouse Moved");
}
AIM
Write a Java program that works as a simple calculator. Use a grid layout to
arrange buttons for the digits and for the +, -,*, % operations. Add a text field to
display the result. Handle any possible exceptions like divide
by zero.
PROCEDURE
1. Create a JFrame with a BorderLayout.
2. Add a JTextField to display calculations.
3. Create a JPanel with a GridLayout for buttons.
4. Add buttons for digits 0-9, operators (+, -, *, /), and equals.
5. Implement ActionListener for buttons:
- Handle digit buttons: append digit to display field.
- Handle operator buttons: store operator and first operand.
- Handle equals button: perform operation and display result.
- Handle clear button: reset display field and operands.
6. Perform operations using a switch statement.
7. Handle exceptions for divide by zero and invalid input.
8. Make frame visible using SwingUtilities.invokeLater.
14.SimpleCalculator.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
String[] buttonLabels = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"C", "0", "=", "+"
};
try {
if (command.matches("\\d")) {
if (isOperatorClicked) {
displayField.setText("");
isOperatorClicked = false;
}
displayField.setText(displayField.getText() + command);
} else if (command.matches("[+\\-*/]")) {
firstOperand = Double.parseDouble(displayField.getText());
operator = command;
isOperatorClicked = true;
} else if (command.equals("=")) {
double secondOperand =
Double.parseDouble(displayField.getText());
double result = performOperation(firstOperand, secondOperand,
operator);
displayField.setText(String.valueOf(result));
} else if (command.equals("C")) {
displayField.setText("");
firstOperand = 0;
operator = "";
}
} catch (ArithmeticException ex) {
displayField.setText("Error: Divide by Zero");
} catch (NumberFormatException ex) {
displayField.setText("Error: Invalid Input");
}
}
AIM
Write 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.
PROCEDURE
1. Create a JFrame with a BorderLayout.
2. Add a JLabel to display traffic light messages.
3. Create a JPanel with a GridLayout for radio buttons.
4. Add radio buttons for red, yellow, and green traffic lights.
5. Group radio buttons using a ButtonGroup.
6. Implement ActionListener for radio buttons:
- Update JLabel text and color based on selected traffic light.
7. Make frame visible using SwingUtilities.invokeLater.
15.TrafficLightSimulator.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
redButton.addActionListener(this);
yellowButton.addActionListener(this);
greenButton.addActionListener(this);
buttonPanel.add(redButton);
buttonPanel.add(yellowButton);
buttonPanel.add(greenButton);
add(buttonPanel, BorderLayout.CENTER);
}