Java Programs
Java Programs
import java.util.Scanner;
// Main function
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.close();
}
}
Explanation:
1. isPrime(int num): This method checks if a given number num is prime. It returns false
if the number is less than or equal to 1 or divisible by any number other than 1 and itself.
Otherwise, it returns true.
2. Input: The program asks the user to input a number N, and it will print all prime numbers
up to N.
3. Loop: The program iterates over all numbers from 2 to N and checks if each number is
prime using the isPrime() method.
4. Output: It prints the prime numbers found within the range.
Example:
// Main function
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.close();
}
}
Explanation:
Example:
scanner.close();
}
}
Explanation:
1. Input: The program allows the user to enter multiple lines of text. The user types "exit"
when they are done, and this input is terminated.
2. StringBuilder: The text is accumulated in a StringBuilder object so that multiple lines
can be stored efficiently.
3. Count Characters: The number of characters is calculated by finding the length of the
entire text (inputText.length()).
4. Count Words: The number of words is found by splitting the text by whitespace
(split("\\s+")). This ensures that any number of spaces between words is handled
correctly.
5. Count Lines: The number of lines is calculated by splitting the text by newline
(split("\n")).
6. Display: The program prints the count of characters, words, and lines.
Example:
Enter the text (type 'exit' to stop input and calculate statistics):
Hello world
This is a Java program
To count characters, words, and lines
exit
Number of characters: 75
Number of words: 13
Number of lines: 4
Characters: There are 75 characters in the input (including spaces and newline
characters).
Words: There are 13 words in the input.
Lines: There are 4 lines in the input (including the exit line, but exit is not counted as
text).
4. Java program that generates a random number between two specified
numbers:
import java.util.Random;
import java.util.Scanner;
Explanation:
1. Input: The program first prompts the user to input the lower and upper bounds for
generating the random number.
2. Validation: It checks if the lower bound is less than the upper bound. If not, it displays
an error message.
3. Random Generation:
o The Random class is used to generate the random number.
o The method random.nextInt(upperBound - lowerBound) generates a random
number in the range [0, upperBound - lowerBound). By adding the
lowerBound, we shift the range to [lowerBound, upperBound).
4. Output: It prints the random number generated within the specified bounds.
Example:
import java.util.Scanner;
scanner.close();
}
}
Explanation:
Example:
import java.util.Scanner;
// Extract a substring
if (start >= 0 && end <= str1.length() && start < end) {
String extractedSubstring = extractSubstring(str1, start, end);
System.out.println("Extracted substring: " + extractedSubstring);
} else {
System.out.println("Invalid start or end index for substring
extraction.");
}
scanner.close();
}
}
Explanation:
3. Delete a Substring:
o The delete(int start, int end) method is used to remove a substring from
the StringBuffer.
o The start index is inclusive, and the end index is exclusive. For example,
delete(18, 23) will remove the substring from index 18 to 22 (inclusive).
o Example:
Example Output:
plaintext
Copy code
Original String: Hello, this is a test string!
Length of the string: 30
Reversed String: !gnirts tset a si siht ,olleH
After Deleting Substring: Hello, this is a string!
javac StringBufferOperations.java
java StringBufferOperations
Java Code:
import java.util.Random;
// Second thread that calculates and prints the square if the number is
even
static class SquareCalculator extends Thread {
public void run() {
while (true) {
// Check if the number is even
if (randomNumber % 2 == 0) {
int square = randomNumber * randomNumber;
System.out.println("Square of " + randomNumber + ": " +
square);
}
try {
// Sleep for a short time to avoid busy-waiting
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("SquareCalculator interrupted");
}
}
}
}
// Third thread that calculates and prints the cube if the number is odd
static class CubeCalculator extends Thread {
public void run() {
while (true) {
// Check if the number is odd
if (randomNumber % 2 != 0) {
int cube = randomNumber * randomNumber * randomNumber;
System.out.println("Cube of " + randomNumber + ": " +
cube);
}
try {
// Sleep for a short time to avoid busy-waiting
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("CubeCalculator interrupted");
}
}
}
}
randomThread.start();
squareThread.start();
cubeThread.start();
}
}
Explanation:
1. RandomNumberGenerator Thread:
o This thread generates a random number between 1 and 100 every second
(Thread.sleep(1000)).
o The number is stored in the shared variable randomNumber.
2. SquareCalculator Thread:
o This thread continuously checks if the randomNumber is even. If it is, it computes
the square of the number and prints it.
o It sleeps for 500 milliseconds to avoid busy-waiting and to allow other threads to
run.
3. CubeCalculator Thread:
o This thread continuously checks if the randomNumber is odd. If it is, it computes
the cube of the number and prints it.
o It also sleeps for 500 milliseconds to avoid busy-waiting.
Key Points:
The program uses a shared variable randomNumber to communicate the random number
generated by the first thread with the second and third threads.
All threads run continuously in an infinite loop. They perform their respective tasks
(generating a random number, computing square or cube) and then sleep for a short
period to avoid overloading the CPU.
Threads are synchronized with sleep intervals to allow them to run efficiently and not
consume unnecessary CPU time.
Example Output:
Generated number: 75
Cube of 75: 421875
Generated number: 32
Square of 32: 1024
Generated number: 11
Cube of 11: 1331
Generated number: 48
Square of 48: 2304
9. Java program that demonstrates how to use threads asynchronously to
print the numbers from 1 to 10 using Thread1 and from 90 to 100 using
Thread2. The program uses the same method in both threads to print
numbers, but each thread prints a different range of numbers:
Java Code:
public class AsynchronousThreadExample {
Explanation:
1. printNumbers Method:
o This method takes two arguments, start and end, and prints numbers from
start to end.
o It uses Thread.sleep(100) to simulate a small delay (100 milliseconds) between
printing each number. This helps illustrate asynchronous behavior.
2. Thread1 and Thread2 Classes:
o Thread1 calls the printNumbers method to print numbers from 1 to 10.
o Thread2 calls the printNumbers method to print numbers from 90 to 100.
3. main Method:
o Instances of Thread1 and Thread2 are created and started asynchronously by
calling their start() method.
4. Synchronization:
o The printNumbers method is marked as synchronized to ensure that even
though both threads use the same method, they do not print numbers
simultaneously in an interleaved way. This helps prevent thread interference or
inconsistent output when multiple threads try to access the same method at the
same time.
Output Example:
Copy code
1
2
3
4
5
6
7
8
9
10
90
91
92
93
94
95
96
97
98
99
100
10.Java program that demonstrates the use of the following exceptions:
Java Code:
public class ExceptionDemo {
Explanation of Exceptions:
1. ArithmeticException:
o Occurs when an illegal arithmetic operation is performed. In the example,
division by zero (10 / 0) throws an ArithmeticException.
o The message "divide by zero" is captured by the exception handler.
2. NumberFormatException:
o Occurs when trying to convert a string to a number, but the string does not have a
valid format. In this case, we try to parse "abc" as an integer, which is invalid.
o The parseInt("abc") will throw a NumberFormatException.
3. ArrayIndexOutOfBoundsException:
o Occurs when trying to access an array element using an invalid index. In this case,
we try to assign a value to arr[10], but the array only has indices 0 to 4, so an
ArrayIndexOutOfBoundsException is thrown.
4. NegativeArraySizeException:
o Occurs when trying to create an array with a negative size. The line new int[-5]
tries to create an array with a negative size, which throws a
NegativeArraySizeException.
Example Output:
Arithmetic Exception: / by zero
Number Format Exception: For input string: "abc"
Array Index Out of Bound Exception: Index 10 out of bounds for length 5
Negative Array Size Exception: Size of array is negative
11. Java program that reads a file name from the user and displays the
following information about the file:
Java Code:
import java.io.File;
import java.util.Scanner;
} else {
System.out.println("File does not exist.");
}
Explanation:
1. File object: A File object is created using the file name provided by the user. The File
class is part of java.io package, and it provides various methods to get information
about the file.
2. Checking file existence:
o file.exists() returns true if the file exists, otherwise false.
5. File size:
o file.length() returns the size of the file in bytes.
Example Output:
Java Code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
// Components
private JTextArea textArea;
private JComboBox<String> fontSizeComboBox;
private JCheckBox boldCheckBox, italicCheckBox;
public TextEditorApp() {
// Set frame title and layout
setTitle("Text Editor with Font and Style Options");
setLayout(new BorderLayout());
// Bold checkbox
boldCheckBox = new JCheckBox("Bold");
boldCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateTextStyle();
}
});
controlPanel.add(boldCheckBox);
// Italic checkbox
italicCheckBox = new JCheckBox("Italic");
italicCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateTextStyle();
}
});
controlPanel.add(italicCheckBox);
1. JTextArea: This is where the user can enter the text. It is wrapped inside a JScrollPane
to make it scrollable when the text becomes long.
2. JComboBox: This dropdown menu allows the user to select the font size. We use an
array of font sizes (fontSizes), and the selected item in the JComboBox is used to update
the font size of the text in the JTextArea.
3. JCheckBox: There are two checkboxes:
o One for enabling/disabling bold.
o One for enabling/disabling italic.
These checkboxes allow the user to toggle the respective styles on or off.
4. Font update logic: The updateTextStyle method is called whenever the user interacts
with the controls. It checks the current settings of the font size, bold, and italic options
and updates the font style of the text area accordingly.
5. Swing GUI components: The frame (JFrame) contains a central text area for input and a
control panel at the top for selecting the font size and toggling bold/italic options.
6. Main method: The application is run inside the main method, and the GUI is made
visible by calling setVisible(true) on the frame.
When the program starts, a text area appears with a default font size of 14 and no bold or
italic styles.
The user can change the font size by selecting a different option in the combo box.
The user can toggle bold or italic by checking or unchecking the respective checkboxes.
The text area updates in real-time as the user changes any of the options.
Example Output:
After typing text, the user can change the font size, make the text bold or italic, and the changes
will reflect in the text area immediately.
Java Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Components declaration
private JTextArea textArea;
private JComboBox<String> fontComboBox, sizeComboBox;
private JCheckBox boldCheckBox, italicCheckBox;
private JButton applyButton;
public FontChangerApp() {
// Set up the JFrame properties
setTitle("Font and Style Changer");
setSize(600, 400);
setLocationRelativeTo(null); // Center the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Apply button
applyButton = new JButton("Apply");
// Apply the selected font, size, and style to the text area
textArea.setFont(new Font(selectedFont, style, selectedSize));
}
});
}
1. Components:
o JTextArea: This area is where the user can type the text. It is initialized with
some default text ("Enter text here...").
o JComboBox<String> (fontComboBox, sizeComboBox): These combo boxes are
used to select the font family and font size.
o JCheckBox (boldCheckBox, italicCheckBox): These checkboxes let the user
toggle the Bold and Italic styles.
o JButton (applyButton): A button to apply the selected font family, size, and style
to the text area.
2. Layout:
o The JFrame uses a BorderLayout. The JTextArea is placed in the center of the
frame, and the control panel (which holds the combo boxes, checkboxes, and the
apply button) is placed at the bottom (south).
3. Font Application:
o When the user clicks the Apply button, an ActionListener is triggered. This
listener fetches the selected font family, size, and style. Based on the selected
options, the style is calculated (Font.BOLD, Font.ITALIC, or both). Then, the font
is applied to the JTextArea by creating a new Font object and calling setFont()
on the JTextArea.
4. Font Style Calculation:
o The program checks whether both Bold and Italic are selected. If both are
selected, the style is set to both Font.BOLD and Font.ITALIC. If only one is
selected, it applies the respective style.
1. Text Area: The user can enter any text into the JTextArea. This is the area where the
font and style changes will be applied.
2. Font and Size Selection: The user can select the font family and font size from the
combo boxes.
3. Bold and Italic: The user can toggle Bold and Italic using the checkboxes.
4. Apply Button: Once the user has selected the desired font family, size, and styles, they
can click the Apply button, which will update the text in the JTextArea with the new
font settings.
Example Output:
javac FontChangerApp.java
java FontChangerApp
A window will appear where you can input text and adjust its font, size, and style using the
provided controls.
Key Components:
13. Java program, we will handle all mouse events (mouse clicked, mouse
pressed, mouse released, mouse entered, and mouse exited) using
MouseAdapter. When a mouse event is triggered, the event's name will be
displayed at the center of the window.
Steps:
Java Code:
import java.awt.*;
import java.awt.event.*;
1. MouseEventDemo Class:
o This class extends Frame, a top-level window provided by AWT.
o We have a String eventName to store the name of the event that is triggered
(e.g., "Mouse Clicked").
o We use the addMouseListener method to listen for mouse events. The
MouseAdapter class is used so we can override only the methods we need.
2. MouseAdapter:
o The mouseClicked(), mousePressed(), mouseReleased(), mouseEntered(),
and mouseExited() methods are overridden to capture each specific mouse
event.
o Whenever an event occurs, the eventName variable is updated with the
corresponding event name, and repaint() is called to trigger a redraw of the
window.
3. Painting the Event Name:
o The paint() method is overridden to display the eventName at the center of the
window.
o We calculate the width and height of the event name text using FontMetrics to
ensure it's centered both horizontally and vertically.
4. Frame Setup:
o The frame is created with the title "Mouse Event Handler" and is set to be visible
at the center of the screen with a size of 400x400 pixels.
Example Output:
1. Clicking the mouse will display "Mouse Clicked" at the center of the window.
2. Pressing the mouse will display "Mouse Pressed".
3. Releasing the mouse will display "Mouse Released".
4. Entering the window with the mouse will display "Mouse Entered".
5. Exiting the window with the mouse will display "Mouse Exited".
14. Java program that implements a simple calculator with a graphical user
interface (GUI) using the GridLayout to arrange buttons for digits and
arithmetic operations. The calculator supports basic operations such as
addition, subtraction, multiplication, division, and modulus, and handles
division by zero exceptions.
// Declare components
private TextField display;
private String currentInput = ""; // To hold the current input
private double result = 0; // To hold the result of operations
private String operator = ""; // To hold the operator (+, -, *, /, %)
public SimpleCalculator() {
// Set the frame layout and title
setTitle("Simple Calculator");
setSize(400, 500);
setLocationRelativeTo(null); // Center the window
setLayout(new BorderLayout());
add(panel, BorderLayout.CENTER);
if (expression.contains("+")) {
tokens = expression.split("\\+");
result = Double.parseDouble(tokens[0]) +
Double.parseDouble(tokens[1]);
} else if (expression.contains("-")) {
tokens = expression.split("-");
result = Double.parseDouble(tokens[0]) -
Double.parseDouble(tokens[1]);
} else if (expression.contains("*")) {
tokens = expression.split("\\*");
result = Double.parseDouble(tokens[0]) *
Double.parseDouble(tokens[1]);
} else if (expression.contains("/")) {
tokens = expression.split("/");
if (Double.parseDouble(tokens[1]) == 0) {
throw new ArithmeticException("Divide by zero");
}
result = Double.parseDouble(tokens[0]) /
Double.parseDouble(tokens[1]);
} else if (expression.contains("%")) {
tokens = expression.split("%");
result = Double.parseDouble(tokens[0]) %
Double.parseDouble(tokens[1]);
}
return result;
}
1. Frame Layout:
o We use a BorderLayout for the main frame with the TextField at the top for
displaying the result.
o The buttons for digits and operators are arranged using a GridLayout in a 4x4
grid. This includes digits 0-9, arithmetic operators (+, -, *, /, %), and an "="
button for evaluation.
2. TextField:
o TextField display is used to show the current expression or result. It is set to
be non-editable (setEditable(false)) so the user can only see the result.
3. Buttons:
o The buttons for digits (0-9) and operators are created dynamically and added to
the panel.
o Each button has an ActionListener attached to handle clicks and update the
currentInput or perform the calculation when "=" is clicked.
4. ButtonClickListener:
o The ButtonClickListener class is responsible for handling button clicks. When
a button is clicked:
If "=" is clicked, the expression is evaluated using
evaluateExpression().
If an operator is clicked, it stores the current input and operator.
Otherwise, it appends the clicked digit or decimal point to the
currentInput.
5. Evaluation Logic:
o The evaluateExpression method evaluates the mathematical expression based
on the operator. It splits the expression by the operator, performs the calculation,
and returns the result.
o The method handles division by zero by throwing an ArithmeticException.
6. Error Handling:
o If the user tries to divide by zero, the program catches the exception and displays
"Error" in the text field.
7. Closing the Frame:
o The window will close when the user clicks the close button by listening to the
WindowAdapter.
Example Usage:
When the program is run, you will see a simple calculator window with buttons for digits,
arithmetic operators, and an "=" button for calculating the result.
For example:
o Click 5, +, 3, and then = to get the result 8.
o If you click 10, /, 0, and then =, it will display "Error" since dividing by zero is
not allowed.
15. To simulate a traffic light system using Java, we can utilize Swing
components, which are a part of the Java Foundation Classes (JFC). We'll use
a JRadioButton for the three traffic light colors (red, yellow, and green), and
depending on the user's selection, an appropriate message ("stop", "ready",
or "go") will appear above the buttons in the selected color.
Java Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Declare components
private JRadioButton redButton, yellowButton, greenButton;
private JLabel messageLabel;
private ButtonGroup buttonGroup;
public TrafficLightSimulator() {
// Set up the frame
setTitle("Traffic Light Simulator");
setSize(400, 300);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Initialize components
redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");
1. JRadioButton:
o Three radio buttons are created for the red, yellow, and green traffic lights:
redButton, yellowButton, and greenButton.
o JRadioButton is used because it allows only one button to be selected at a time
when grouped together with ButtonGroup.
2. ButtonGroup:
o We group the radio buttons (redButton, yellowButton, and greenButton) using
a ButtonGroup. This ensures that only one radio button can be selected at a time.
3. JLabel:
o messageLabel is a JLabel used to display the traffic light message ("Stop",
"Ready", "Go"). Initially, it displays nothing ("").
o The label's text color is set dynamically based on the selected radio button.
4. ActionListener:
o An ActionListener is added to each radio button. When a radio button is
selected, the appropriate message is displayed in the label with the corresponding
color (red, yellow, or green).
5. FlowLayout:
o A FlowLayout is used to arrange the components in a simple and clean manner.
The message is displayed at the top, followed by the three radio buttons arranged
vertically.
6. Font and Appearance:
o The font of the message label is set to be bold and of size 20 for better visibility.
o The color of the message label changes according to the selected traffic light.
7. Main Method:
o In the main method, we create an instance of the TrafficLightSimulator class,
which sets up the GUI and makes it visible.
Key Components:
Example Output:
1. When the Red radio button is selected, the label will show "Stop" in red color.
2. When the Yellow radio button is selected, the label will show "Ready" in yellow color.
3. When the Green radio button is selected, the label will show "Go" in green color.
javac TrafficLightSimulator.java
java TrafficLightSimulator