[Go to site: main page, start]

0% found this document useful (0 votes)
2 views50 pages

Java Program

The document contains several Java programs that demonstrate various programming concepts, including generating prime numbers, multiplying matrices, counting characters in a text file, generating random numbers, performing string manipulations, and handling exceptions. It also includes multi-threading examples and file handling to check file properties. Each program is presented with input and output sections, showcasing the functionality of Java in different scenarios.

Uploaded by

stharsana955
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views50 pages

Java Program

The document contains several Java programs that demonstrate various programming concepts, including generating prime numbers, multiplying matrices, counting characters in a text file, generating random numbers, performing string manipulations, and handling exceptions. It also includes multi-threading examples and file handling to check file properties. Each program is presented with input and output sections, showcasing the functionality of Java in different scenarios.

Uploaded by

stharsana955
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA PROGRAM

1. Write a Java program that prompts the user for an integer and then prints out all the prime
numbers up to that Integer?

INPUT:

import [Link];
class primenum1
{
public void primegen()
{
Scanner sc=new Scanner([Link]);
[Link]("Enter the number limit for prime number");
int num= [Link]();
int count;
[Link]("\n list of prime numbers upto"+num);
for(int i=2;i<=num;i++)
{
count=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
count=count+1;
}
if(count==0)
[Link](i);
}
}
}
public class primenum
{
public static void main (String args[])
{
primenum1 obj=new primenum1();
[Link]();
}
}
OUTPUT:
2. Write a Java program to multiply two given matrices.

INPUT:

public class MultiplyMatrices {


public static void main(String[] args) {

int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;

int[][] firstMatrix = {
{3, -2, 5},
{3, 0, 4}
};

int[][] secondMatrix = {
{2, 3},
{-9, 0},
{0, 4}
};

int[][] product = new int[r1][c2];

// Matrix multiplication
for (int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}

// Display result
[Link]("Multiplication of two matrices is:");
for (int[] row : product) {
for (int column : row) {
[Link](column + " ");
}
[Link]();
}
}
}
OUTPUT:
3. Write a Java program that displays the number of characters, lines and words in a text?

INPUT:

import [Link];
import [Link];
import [Link];

public class Count1 {


public static void main(String[] args) {

int charCount = 0;
int wordCount = 0;
int lineCount = 0;

try (BufferedReader reader = new BufferedReader(


new FileReader("D:\\[Link]"))) {

String currentLine;

while ((currentLine = [Link]()) != null) {


lineCount++;

// Count characters INCLUDING spaces


charCount += [Link]();

// Count words safely


String[] words = [Link]().split("\\s+");
if (![Link]().isEmpty()) {
wordCount += [Link];
}
}

[Link]("Number Of Characters In File : " + charCount);


[Link]("Number Of Words In File : " + wordCount);
[Link]("Number Of Lines In File : " + lineCount);

} catch (IOException e) {
[Link]();
}
}
}
OUTPUT:
4. Generate random numbers between two given limits using Random class and print
messages according to the range of the value generated.

INPUT:

import [Link];
public class Demo
{
public static int randomNumberGenerator(int min, int max)
{
Random r = new Random();
double randomNum = [Link]();
int result = (int)(randomNum * (max - min)) + min;
return result;
}
public static void main(String[] args)
{
int r1 = randomNumberGenerator(5, 105);
int r2 = randomNumberGenerator(2199, 2200);
[Link]("The first random number is: " + r1);
[Link]("The second random number is: " + r2);
}
}
OUTPUT:
5. Write a program to do String Manipulation using Character Array and perform the
following string operations:

a. String length

b. Finding a character at a particular position

c. Concatenating two strings

INPUT:

import [Link];

public class SM {

public static void main(String[] args) {

// Create a Scanner object for user input

Scanner scanner = new Scanner([Link]);

// Input two strings

[Link]("Enter the first string: ");

String str1 = [Link]();

[Link]("Enter the second string: ");

String str2 = [Link]();

// Convert strings to character arrays

char[] charArray1 = [Link]();

char[] charArray2 = [Link]();

// String length

[Link]("\nLength of the first string: " + [Link]);

[Link]("Length of the second string: " + [Link]);

// Finding a character at a particular position

[Link]("\nEnter the position to find the character in the first string (0-indexed):");

int position = [Link]();

if (position >= 0 && position < [Link]) {


[Link]("Character at position " + position +" in the first string: " +
charArray1[position]);

} else {

[Link]("Invalid position!");

// Concatenating two strings

char[] concatenatedArray = concatenateArrays(charArray1, charArray2);

[Link]("\nConcatenated string: ");

[Link](new String(concatenatedArray));

// Close the scanner

[Link]();

// Method to concatenate two character arrays

public static char[] concatenateArrays(char[] array1, char[] array2) {

char[] result = new char[[Link] + [Link]];

// Copy elements of the first array

for (int i = 0; i < [Link]; i++) {

result[i] = array1[i];

// Copy elements of the second array

for (int i = 0; i < [Link]; i++) {

result[[Link] + i] = array2[i];

return result;

}
OUTPUT:
6. 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

INPUT:

import [Link];

public class StringClass

public static void main(String[] args)

// Create a Scanner object for user input

Scanner scanner = new Scanner([Link]);

// Input two strings

[Link]("Enter the first string: ");

String str1 = [Link]();

[Link]("Enter the second string: ");

String str2 = [Link]();

// a. String Concatenation

String concatenatedString = str1 + str2; // Using the + operator to concatenate strings

[Link]("\nConcatenated String: " + concatenatedString);

// b. Search a Substring

[Link]("\nEnter a substring to search in the first string: ");

String substringToSearch = [Link]();

if ([Link](substringToSearch))

{
[Link]("The substring \"" + substringToSearch + "\" is found in the first
string.");

else

[Link]("The substring \"" + substringToSearch + "\" is not found in the


first string.");

// c. Extract a Substring

[Link]("\nEnter the starting index to extract a substring from the first string:
");

int startIndex = [Link]();

// Extract the substring (we'll assume endIndex is not out of bounds)

if (startIndex >= 0 && startIndex < [Link]())

[Link]("Enter the ending index to extract the substring (exclusive): ");

int endIndex = [Link]();

if (endIndex > startIndex && endIndex <= [Link]())

String extractedSubstring = [Link](startIndex, endIndex);

[Link]("Extracted Substring: " + extractedSubstring);

else

[Link]("Invalid ending index!");

}
else

[Link]("Invalid starting index!");

// Close the scanner

[Link]();

OUTPUT:
7. 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

INPUT:

import [Link];

import [Link];

public class StringOper

public static void main(String[] args)

// Create a Scanner object for user input

Scanner scanner = new Scanner([Link]);

// Input string

[Link]("Enter a string: ");

String inputString = [Link]();

// Create a StringBuffer object from the input string

StringBuffer stringBuffer = new StringBuffer(inputString);

// a. Length of the string

int length = [Link]();

[Link]("\nLength of the string: " + length);

// b. Reverse the string

[Link]();

[Link]("\nReversed string: " + [Link]());

// To maintain the original string, reset the StringBuffer

stringBuffer = new StringBuffer(inputString);


// c. Delete a substring

[Link]("\nEnter the starting index to delete a substring: ");

int startIndex = [Link]();

[Link]("Enter the ending index (exclusive) to delete the substring: ");

int endIndex = [Link]();

if (startIndex >= 0 && endIndex <= [Link]() && startIndex < endIndex)

[Link](startIndex, endIndex);

[Link]("\nString after deletion: " + [Link]());

else

[Link]("\nInvalid indices for deletion!");

// Close the scanner

[Link]();

}
OUTPUT:
8. 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.

INPUT:

import [Link];

public class MultiThreadExample


{
public static void main(String[] args)
{

RandomNumberGenerator generator = new RandomNumberGenerator(10);


SquarePrinter squarePrinter = new SquarePrinter(generator);
CubePrinter cubePrinter = new CubePrinter(generator);

Thread generatorThread = new Thread(generator);


Thread squareThread = new Thread(squarePrinter);
Thread cubeThread = new Thread(cubePrinter);

[Link]();
[Link]();
[Link]();
}
}

class RandomNumberGenerator implements Runnable


{
private int currentNumber;
private int count = 0;
private int maxCount;

public RandomNumberGenerator(int maxCount)


{
[Link] = maxCount;
}

@Override
public void run()
{
Random random = new Random();
while (count < maxCount)
{
try {
currentNumber = [Link](100) + 1;
[Link]("Generated number: " + currentNumber);
count++;

[Link](1000);
} catch (InterruptedException e)
{
[Link]();
}
}
}

public synchronized int getCurrentNumber()


{
return currentNumber;
}

public boolean isFinished()


{
return count >= maxCount;
}
}

class SquarePrinter implements Runnable


{
private RandomNumberGenerator generator;
private int lastPrinted = -1;

public SquarePrinter(RandomNumberGenerator generator)


{
[Link] = generator;
}

@Override
public void run()
{
while (![Link]())
{
try {
int num = [Link]();

if (num % 2 == 0 && num != lastPrinted)


{
int square = num * num;
[Link]("Square of " + num + " is: " + square);
lastPrinted = num;
}

[Link](200);
} catch (InterruptedException e)
{
[Link]();
}
}
}
}

class CubePrinter implements Runnable


{
private RandomNumberGenerator generator;
private int lastPrinted = -1;

public CubePrinter(RandomNumberGenerator generator)


{
[Link] = generator;
}

@Override
public void run()
{
while (![Link]())
{
try {
int num = [Link]();

// Print cube only once per number


if (num % 2 != 0 && num != lastPrinted)
{
int cube = num * num * num;
[Link]("Cube of " + num + " is: " + cube);
lastPrinted = num;
}

[Link](200); // Small delay to sync with generator


} catch (InterruptedException e)
{
[Link]();
}
}
}
}
OUTPUT:
[Link] a threading program which uses the same method asynchronously to print the
numbers 1 to 10 using Thread 1 and to print 90 to 100 using Thread 2.

INPUT:

class NumberPrinter extends Thread {

private final int start;

private final int end;

public NumberPrinter(int start, int end) {

[Link] = start;

[Link] = end;

@Override

public void run() {

printNumbers(start, end);

private void printNumbers(int start, int end) {

for (int i = start; i <= end; i++) {

[Link]([Link]().getName() + ": " + i);

try {

[Link](100); // Sleep to simulate asynchronous behavior

} catch (InterruptedException e) {

[Link]();

}
}

public class AsynchronousNumberPrinter {

public static void main(String[] args) {

NumberPrinter thread1 = new NumberPrinter(1, 10);

NumberPrinter thread2 = new NumberPrinter(90, 100);

[Link]("Thread-1");

[Link]("Thread-2");

[Link]();

[Link]();

OUTPUT:
10. Write a program to demonstrate the use of following exceptions.

a. ArithmeticException

b. NumberFormatException

c. ArrayIndexOutofBoundException

d. NegativeArraySizeException

INPUT:

public class ExceptionDemo

public static void main(String[] args)

// Demonstrating ArithmeticException

try

int result = 10 / 0; // Dividing by zero will cause ArithmeticException

catch (ArithmeticException e)

[Link]("ArithmeticException: " + [Link]());

// Demonstrating NumberFormatException

try

String invalidNumber = "abc123";

int num = [Link](invalidNumber); // Invalid number format

catch (NumberFormatException e)
{

[Link]("NumberFormatException: " + [Link]());

// Demonstrating ArrayIndexOutOfBoundsException

try

int[] arr = new int[5];

arr[10] = 50; // Accessing an invalid index

catch (ArrayIndexOutOfBoundsException e)

[Link]("ArrayIndexOutOfBoundsException: " +

[Link]());

// Demonstrating NegativeArraySizeException

try

int size = -5;

int[] arr = new int[size]; // Array size cannot be negative

catch (NegativeArraySizeException e)

[Link]("NegativeArraySizeException: " + [Link]());

}
OUTPUT:
11. 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?

INPUT:

import [Link];

import [Link];

public class FileInfo

public static void main(String[] args)

// Create a Scanner object to read input from the user

Scanner scanner = new Scanner([Link]);

// Prompt the user to enter a file name

[Link]("Enter the file name (with full path if necessary): ");

String fileName = [Link]();

// Create a File object using the file name

File file = new File(fileName);

// Check if the file exists

if ([Link]())

[Link]("File exists: Yes");

// Check if the file is readable

[Link]("Readable: " + [Link]());

// Check if the file is writable

[Link]("Writable: " + [Link]());

// Check if it's a regular file or a directory


if ([Link]())

[Link]("It is a regular file.");

else if ([Link]())

[Link]("It is a directory.");

else

[Link]("It is neither a regular file nor a directory.");

// Display the file size (in bytes)

[Link]("File length (in bytes): " + [Link]());

else

[Link]("File does not exist.");

// Close the scanner to avoid resource leak

[Link]();

}
OUTPUT:
[Link] a program to accept a text and change its size and font. Include

Bold italic options. Use frames and controls.

INPUT:

import [Link].*;

import [Link].*;

import [Link].*;

public class TextE

public static void main(String[] args)

// Create the frame for the application

JFrame frame = new JFrame("Text Editor with Font Controls");

[Link](JFrame.EXIT_ON_CLOSE);

[Link](600, 400);

[Link](new BorderLayout());

// Create a JTextArea to accept text

JTextArea textArea = new JTextArea();

[Link](new Font("Arial", [Link], 14)); // Default font

JScrollPane scrollPane = new JScrollPane(textArea);

[Link](scrollPane, [Link]);

// Create a panel for font size and style controls

JPanel controlPanel = new JPanel();

[Link](new FlowLayout());

// Font size adjustment

JLabel sizeLabel = new JLabel("Font Size:");

[Link](sizeLabel);
// Font size slider

JSlider fontSizeSlider = new JSlider(10, 50, 14); // Range: 10 to 50

[Link](10);

[Link](1);

[Link](true);

[Link](true);

[Link](fontSizeSlider);

// Bold and Italic checkboxes

JCheckBox boldCheckBox = new JCheckBox("Bold");

JCheckBox italicCheckBox = new JCheckBox("Italic");

[Link](boldCheckBox);

[Link](italicCheckBox);

// Add the control panel to the frame

[Link](controlPanel, [Link]);

// Add an action listener to the font size slider

[Link](e ->

int fontSize = [Link]();

int style = 0;

if ([Link]() && [Link]())

style = [Link] | [Link];

else if ([Link]())

style = [Link];

}
else if ([Link]())

style = [Link];

[Link](new Font("Arial", style, fontSize));

);

// Add action listeners to checkboxes

[Link](e ->

int fontSize = [Link]();

int style = 0;

if ([Link]() && [Link]())

style = [Link] | [Link];

else if ([Link]())

style = [Link];

} else if ([Link]())

style = [Link];

[Link](new Font("Arial", style, fontSize));

});

[Link](e ->

{
int fontSize = [Link]();

int style = 0;

if ([Link]() && [Link]())

style = [Link] | [Link];

else if ([Link]())

style = [Link];

else if ([Link]())

style = [Link];

[Link](new Font("Arial", style, fontSize));

});

// Show the frame

[Link](true);

}
OUTPUT:

[Link] 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).

INPUT:

import [Link].*;

import [Link].*;

import [Link].*;

public class MouseEventDemo extends JFrame

private String eventName = "No Event"; // Initially, no event

// Constructor to set up the JFrame

public MouseEventDemo()

setTitle("Mouse Event Demo");

setSize(400, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Add a MouseAdapter to handle mouse events

addMouseListener(new MouseAdapter()

@Override

public void mousePressed(MouseEvent e)

eventName = "Mouse Pressed";

repaint();

}
@Override

public void mouseReleased(MouseEvent e)

eventName = "Mouse Released";

repaint();

@Override

public void mouseClicked(MouseEvent e)

eventName = "Mouse Clicked";

repaint();

@Override

public void mouseEntered(MouseEvent e)

eventName = "Mouse Entered";

repaint();

@Override

public void mouseExited(MouseEvent e)

eventName = "Mouse Exited";

repaint();

}
});

// Add a MouseMotionAdapter to handle mouse movement events

addMouseMotionListener(new MouseAdapter()

@Override

public void mouseMoved(MouseEvent e)

eventName = "Mouse Moved";

repaint();

@Override

public void mouseDragged(MouseEvent e)

eventName = "Mouse Dragged";

repaint();

});

// Overriding the paint method to draw the event name at the center

@Override

public void paint(Graphics g)

[Link](g); // Call the superclass's paint method to ensure the background is cleared

// Set up the graphics

[Link]([Link]);
[Link](new Font("Arial", [Link], 16));

// Get the dimensions of the window

Dimension dimension = getSize();

int x = [Link] / 2;

int y = [Link] / 2;

// Draw the event name at the center of the window

FontMetrics fm = [Link]();

int textWidth = [Link](eventName);

int textHeight = [Link]();

// Center the text

[Link](eventName, x - textWidth / 2, y + textHeight / 4);

// Main method to start the program

public static void main(String[] args)

[Link](() ->

MouseEventDemo frame = new MouseEventDemo();

[Link](true);

});

OUTPUT:
[Link] 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.

INPUT:

import [Link].*;

import [Link].*;

import [Link].*;

public class SimpleCalculator extends JFrame {

private JTextField textField;

private double num1 = 0, num2 = 0;

private String operator = "";

private boolean operatorPressed = false;

public SimpleCalculator() {

setTitle("Simple Calculator");

setSize(400, 500);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

textField = new JTextField();

[Link](false);

[Link](new Font("Arial", [Link], 24));

[Link]([Link]);

add(textField, [Link]);

JPanel panel = new JPanel();


[Link](new GridLayout(4, 4, 10, 10));

String[] buttons = {

"7","8","9","/",

"4","5","6","*",

"1","2","3","-",

"0",".","=","+"

};

for (String label : buttons) {

JButton button = new JButton(label);

[Link](new Font("Arial", [Link], 20));

[Link](new ButtonClickListener());

[Link](button);

add(panel, [Link]);

private class ButtonClickListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

String command = [Link]();

try {

if ([Link]("=")) {

num2 = [Link]([Link]());

switch (operator) {
case "+": [Link]([Link](num1 + num2)); break;

case "-": [Link]([Link](num1 - num2)); break;

case "*": [Link]([Link](num1 * num2)); break;

case "/":

if (num2 == 0)

[Link]("Error");

else

[Link]([Link](num1 / num2));

break;

operatorPressed = false;

} else if ([Link]("+") || [Link]("-")

|| [Link]("*") || [Link]("/")) {

num1 = [Link]([Link]());

operator = command;

operatorPressed = true;

[Link]("");

} else {

[Link]([Link]() + command);

} catch (Exception ex) {

[Link]("Error");

}
}

public static void main(String[] args) {

[Link](() -> {

new SimpleCalculator().setVisible(true);

});

OUTPUT:
[Link] 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

INPUT:

import [Link].*;

import [Link].*;

import [Link].*;

public class SimpleCalculator extends JFrame {

private JTextField textField;

private double num1 = 0, num2 = 0;

private String operator = "";

private boolean operatorPressed = false;

public SimpleCalculator() {

setTitle("Simple Calculator");

setSize(400, 500);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

textField = new JTextField();

[Link](false);

[Link](new Font("Arial", [Link], 24));

[Link]([Link]);
add(textField, [Link]);

JPanel panel = new JPanel();

[Link](new GridLayout(4, 4, 10, 10));

String[] buttons = {

"7","8","9","/",

"4","5","6","*",

"1","2","3","-",

"0",".","=","+"

};

for (String label : buttons) {

JButton button = new JButton(label);

[Link](new Font("Arial", [Link], 20));

[Link](new ButtonClickListener());

[Link](button);

add(panel, [Link]);

private class ButtonClickListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

String command = [Link]();


try {

if ([Link]("=")) {

num2 = [Link]([Link]());

switch (operator) {

case "+": [Link]([Link](num1 + num2)); break;

case "-": [Link]([Link](num1 - num2)); break;

case "*": [Link]([Link](num1 * num2)); break;

case "/":

if (num2 == 0)

[Link]("Error");

else

[Link]([Link](num1 / num2));

break;

operatorPressed = false;

} else if ([Link]("+") || [Link]("-")

|| [Link]("*") || [Link]("/")) {

num1 = [Link]([Link]());

operator = command;

operatorPressed = true;

[Link]("");

} else {

[Link]([Link]() + command);
}

} catch (Exception ex) {

[Link]("Error");

public static void main(String[] args) {

[Link](() -> {

new SimpleCalculator().setVisible(true);

});

OUTPUT:

You might also like