0% found this document useful (0 votes)
18 views

java prictical for read and zerox

The document contains multiple Java programming tasks, including generating prime numbers, matrix multiplication, string manipulation, handling exceptions, and creating GUI applications for various functionalities such as a calculator and a traffic light simulator. Each task is accompanied by a code snippet and its expected output. The programs cover a range of concepts including multi-threading, file handling, and event handling in Java.

Uploaded by

ai& ds
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

java prictical for read and zerox

The document contains multiple Java programming tasks, including generating prime numbers, matrix multiplication, string manipulation, handling exceptions, and creating GUI applications for various functionalities such as a calculator and a traffic light simulator. Each task is accompanied by a code snippet and its expected output. The programs cover a range of concepts including multi-threading, file handling, and event handling in Java.

Uploaded by

ai& ds
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

1.

Write a java program that prompts the user for an


integer and then print out all the prime number up to that
integer?
public class PrimeNumbers
{
public static void main(String[] args)
{
for (int i = 2; i <= 20; i++)
{
boolean prime = true;
for (int j = 2; j < i; j++)
{
if (i % j == 0) prime = false;
}
if (prime) System.out.println(i);
}
}
}
Output
2
3
5
7
11
13
17
19
2. write a java program to multiply two given matrices.
public class MatrixMultiplication
{
public static void main(String[] args)
{
int[][] a = {{1, 2}, {3, 4}};
int[][] b = {{5, 6}, {7, 8}};
int[][] c = new int[2][2];

for (int i = 0; i < 2; i++)


for (int j = 0; j < 2; j++)
c[i][j] = a[i][0] * b[0][j] + a[i][1] * b[1][j];

for (int[] row : c)


{
for (int num : row) System.out.print(num + " ");
System.out.println();
}
}
}
Output
19 22
43 50
3. Write a java program that displays the number of
characters, lines and words in a text?

public class CountText


{
public static void main(String[] args)
{
String text = "Hello world\nJava is fun";
int characters = text.length();
int words = text.split("\\s+").length;
int lines = text.split("\n").length;

System.out.println("Characters: " + characters);


System.out.println("Words: " + words);
System.out.println("Lines: " + lines);
}
}
Output:
Characters: 23
Words: 5
Line: 2
4. Generate random numbers between two given limits
using random class and print message according to the
range of the value of the generated.

import java.util.Random;
public class RandomNumbers
{
public static void main(String[] args)
{
Random random = new Random();
int num = random.nextInt(50) + 1;
System.out.println("Random number: " + num);
if (num < 20) System.out.println("Less than 20");
else System.out.println("20 or more");
}
}
Out put :

Random number: 12
Less than 20
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

public class StringManipulation


{
public static void main(String[] args)
{
String str = "Hello";
char[] charArray = str.toCharArray();

System.out.println("Length: " + charArray.length);


System.out.println("Character at index 2: " + charArray[2]);
System.out.println("Concatenation: " + new
String(charArray) + " World");
}
}
Output

Length: 5
Character at index 2: l
Concatenation: Hello World
6. Writing a program to perform a following a string
operation using string class:
a) String concatenation
b) to extract Substring from the given string

public class StringOperations


{
public static void main(String[] args)
{
String str = "Java Programming";
System.out.println("Concatenation: " + str.concat(" is
fun"));
System.out.println("Substring: " + str.substring(5));
}
}
Output

Java is fun
Programming
7) write a program to perform the following the string
operations using string buffer class:
a) Length of a string
b) Reverse a string
c) Delete a substring from the given String

public class StringBufferExample


{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("Length: " + sb.length());
System.out.println("Reverse: " + sb.reverse());
System.out.println("Delete: " + sb.delete(1, 3));
}
}
Output

Length: 5
Reverse: olleH
Delete: oeH
8. write a java program that implements a multi-threading
application that had three threads, first thread generates
random integer every I 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 the cube of the number.

import java.util.Random;
class RandomThread extends Thread {
public static volatile int num;
public void run() {
Random r = new Random();
while (true) {
num = r.nextInt(50) + 1;
System.out.println("Generated: " + num);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SquareThread extends Thread {
public void run() {
while (true) {
synchronized (RandomThread.class) {
if (RandomThread.num % 2 == 0) {
System.out.println("Square: " + (RandomThread.num *
RandomThread.num));
}
}
}
}
}

class CubeThread extends Thread {


public void run() {
while (true) {
synchronized (RandomThread.class) {
if (RandomThread.num % 2 != 0) {
System.out.println("Cube: " + (RandomThread.num *
RandomThread.num * RandomThread.num));
}
}
}
}
}

public class MultiThreadShort {


public static void main(String[] args) {
new RandomThread().start();
new SquareThread().start();
new CubeThread().start
}
}
Output
Generated: 12
Square: 144
Generated: 35
Cube: 42875
Generated: 7
Cube: 343
Generated: 20
Square: 400
Generated: 13
Cube: 2197
Generated: 18
Square: 324
9. Write a threading program which uses the same
program asynchronously to print the number 1 to 10
using thread 1 and to print 90 to 100 using thread 2.

public class AsyncThreads


{
public static void main(String[] args)
{
Thread t1 = new Thread(() -> { for (int i = 1; i <= 10; i++)
System.out.println(i); });
Thread t2 = new Thread(() -> { for (int i = 90; i <= 100; i++)
System.out.println(i); });

t1.start();
t2.start();
}
}
Output
1
2
3
4
5
6
7
8
90
91
92
93
94
95
96
97
98
99
100
10. Write a program to demonstrate the use of following
exceptions.
a) Arithmetic Exception
b) Number Format Exception
c) Array Index Out of Bound Exception
d) Negative Array Size Exception

public class Exceptions


{
public static void main(String[] args)
{
try
{
int a = 5 / 0;
} catch (ArithmeticException e)
{
System.out.println("Arithmetic Exception occurred");
}
try {
int num = Integer.parseInt("abc");
}
catch (NumberFormatException e)
{
System.out.println("Number Format Exception
occurred");
}

Try
{
int[] arr = new int[5];
System.out.println(arr[10]);
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Array Index Out Of Bounds Exception
occurred");
}

Try
{
int[] arr = new int[-5];
}
catch (NegativeArraySizeException e)
{
System.out.println("Negative Array Size Exception
occurred");
}
}
}
Output:
Java exception
Arithmetic exception occurred
Number format exception occurred
Array index out of boundaries Exception occurred
Negative array size exceptions occurred
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?

import java.io.File;
import java.util.Scanner;
public class FileInfo
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter file name: ");
String fileName = sc.nextLine();
File file = new File(fileName);
if (file.exists())
{
System.out.println("File exists");
System.out.println("Readable: " + file.canRead());
System.out.println("Writable: " + file.canWrite());
System.out.println("File type: " + (file.isDirectory() ?
"Directory" : "File"));
System.out.println("File size: " + file.length() + " bytes");
} else
{
System.out.println("File does not exist");
}
}
}
Output:
Enter the file name :
Sample.txt
Readable: true
Writable: true
File type: File
File Size: 74 bites
12. Write a program to accept a text and change its size
and font. Include bold italic options. Use frames and
controls.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
public class TextStyleShort
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Text Styler");
JTextField textField = new JTextField("Sample Text");
JCheckBox bold = new JCheckBox("Bold"), italic = new
JCheckBox("Italic");
JButton apply = new JButton("Apply");
frame.setLayout(new GridLayout(3, 1));
frame.add(textField);
frame.add(bold);
frame.add(italic);
frame.add(apply);
apply.addActionListener(e -> textField.setFont(new
Font("Arial", (bold.isSelected() ? Font.BOLD : 0) +
(italic.isSelected() ? Font.ITALIC : 0), 20)));
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:
13. 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).

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MouseEventsExample extends JFrame


{
JLabel label;

public MouseEventsExample()
{
label = new JLabel("", SwingConstants.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 24));
add(label);

addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent e) {
label.setText("Mouse Clicked"); }
public void mouseEntered(MouseEvent e) {
label.setText("Mouse Entered"); }
public void mouseExited(MouseEvent e) {
label.setText("Mouse Exited"); }
});

setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}

public static void main(String[] args)


{
new MouseEventsExample();
}
}
Output:
14. 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.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class Calculator


{
public static void main(String[] args)
{
JFrame frame = new JFrame("Calculator");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(5, 4));

JTextField resultField = new JTextField();


frame.add(resultField, BorderLayout.NORTH);

String[] buttons = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"C", "0", "=", "/"
};

for (String text : buttons)


{
JButton button = new JButton(text);
frame.add(button);
button.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String command = e.getActionCommand();
if (command.equals("="))
{
Try
{
resultField.setText(eval(resultField.getText()));
}
catch (Exception ex) {
resultField.setText("Error");
}
} else if (command.equals("C"))
{
resultField.setText("");
} else
{
resultField.setText(resultField.getText() +
command);
}
}
});
}

frame.setVisible(true);
}

private static String eval(String expression)


{
try{
return String.valueOf((int) new
ScriptEngineManager().getEngineByName("JavaScript").eval(ex
pression));
}catch(ScriptException e){ return "Error";}
}
}
Output:
15. 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.

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class TrafficLight


{
public static void main(String[] args)
{
JFrame frame = new JFrame("Traffic Light");
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();


panel.setLayout(new GridLayout(4, 1));

JRadioButton red = new JRadioButton("Red");


JRadioButton yellow = new JRadioButton("Yellow");
JRadioButton green = new JRadioButton("Green");

ButtonGroup group = new ButtonGroup();


group.add(red);
group.add(yellow);
group.add(green);

JLabel label = new JLabel("", SwingConstants.CENTER);


panel.add(label);
panel.add(red);
panel.add(yellow);
panel.add(green);

red.addActionListener(e -> label.setText("STOP"));


yellow.addActionListener(e -> label.setText("READY"));
green.addActionListener(e -> label.setText("GO"));
frame.add(panel);
frame.setVisible(true);
}
}
Output:

You might also like