Java Programs RE Version2
Java Programs RE Version2
Write a Java program that prompts the user for an integer and then prints out all the
prime numbers up to that Integer
Aim:
To write a Java program that prompts the user for an integer and then prints out all
Algorithm:
Step 2: Read the Input for Prime Number and assign it to variable n.
Program:
// 1. Java Program to implement PrimeNumbers.java
import java.util.Scanner;
class PrimeNumbers
int n;
int p;
for(int i=2;i<n;i++)
p=0;
for(int j=2;j<i;j++)
if(i%j==0)
p=1;
if(p==0)
System.out.println(i);
Output:
Enter a number:
5
the prime nos are
Result:
Thus, the Java program to implement the Prime Numbers has been executed successfully.
*************************************************************************
2. Write a Java program to multiply two given matrices.
Aim:
Algorithm:
Step 4: Multiply firstMatrix with secondMatrix and assign the value to product matrix.
Program:
int r1 = 2, c1 = 2;
int r2 = 2, c2 = 2;
System.out.println("Multiplication of two
matrices is: ");
System.out.println();
}
Output:
14 25
Result:
Thus, the Java program to implement the Matrix Multiplication has been executed successfully.
*****************************************************************
3.Write a Java program that displays the number of characters, lines and words in a text?
AIM:
To write a Java program that displays the number of characters, lines and words in a text
Algorithm:
Program:
// 3. Java Program to displays the number of characters, lines and words in a text
Output:
No.of characters = 34
No.of words = 4
No.of lines = 3
Result:
Thus, the Java program to display displays the number of characters, lines and words in a text
*****************************************************************
4. Generate random numbers between two given limits using Random class and print
messages according to the range of the value generated
Aim:
To write a Java program to Generate random numbers between two given limits using Random
class and print messages according to the range of the value generated
Algorithm:
Step 1: Start the execution.
Step 2: Use Random class to create Random Numbers Generation
Step 3: use nextInt() method to generate random numbers.
Step 4: Check the random Numbers limits to print the range,
Step 5: Display the result.
Step 6: Stop the execution
Program:
// 4. Java Program to Generate random numbers between two given limits using Random class
import java.util.Random;
int min=100;
int max=500;
System.out.println(random.nextInt(max-min+1)+min);
System.out.println(random.nextInt(max-min+1)+min);
System.out.println(random.nextInt(max-min+1)+min);
}
Output:
220
367
202
Result:
Thus, the Java program to implement the Random Numbers between two given limits using
Random class has been executed successfully.
*****************************************************************
5. Write a program to do String Manipulation using Character Array and perform the
following string operations:
a) String length
Aim:
To write a Java program to do String Manipulation using Character Array and perform the
a) String length
Algorithm:
Step 2: Create String class to create string and assign the string
Step 3: Use length() method to find the length of the given string
Program:
strlength
args) {
s1 = first.toCharArray();
Output:
String: Java
String: Dr.murugavel
Result:
Thus, the Java program to implement the String Manipulation using Character Array has been
executed successfully.
*****************************************************************
6. Write a program to perform the following string operations using String class:
a) String Concatenation
b) Search a substring
Aim:
To write a Java program perform the following string operations using String class:
a) String Concatenation
b) Search a substring
Algorithm:
Step 1: Start the execution.
Step 2: Create String object to create string and assign the string value
Step 3: Use concat() method to concatenation of two given string
Step 4: Use substring() method to extract the specified from the given string
Step 5: Use indexOf method to find the string position
Step 6: Display the result
Step 7: Stop the execution
Program:
class strlength
// create a string
System.out.println(str);
}
Output:-
Hello World
Result:
Thus, the Java program to implement the String operations using String class has been executed
successfully.
*****************************************************************
7. Write a program to perform string operations using StringBuffer class:
a) Length of a string
b) Reverse a string
Aim:
a) Length of a string b) Reverse a string c) Delete a substring from the given string
Algorithm:
Step 3: Use length() method to find the length of the given string
Step 4: Use reverse() method to find the length of the given string
Step 5: Use substring() method to extract the specified from the given string
Step 6: Use delete() Method to delete the specified string from the gven string
Program:
Output:
Result:
Thus, the Java program to implement the String operations using String class has been executed
successfully.
*****************************************************************
8. Write a Java program that implements a multi-thread application that has three
threads. First thread generates a random integer for every 1 second; second thread
computes the square of the number and prints; third thread will print the value of
cube of the number.
Aim:
To write a Java program that implements multi-thread application that has three threads.
First thread generates a random integer for every 1 second; second thread computes the
square of
the number and prints; third thread will print the value of cube of the number.
Algorithm:
Step 1: Start the execution.
Step 2: import java.util.Random package
Step 3: Create a Thread and use Random Class to generate random integer for every 1
second
Step 4: Create second Thread to compute square of the number.
Step 5: Create third Thread to compute square of the number
Step 6: Use run() Method to execute the Thread.
Step 7: Display the result
Step 8: Stop the execution
Program:
java.util.Random;
class Square extends Thread
{
int x; Square(int n)
{
x = n;
}
public void run()
{
int sqr = x * x;
System.out.println("Square of " + x + " = " + sqr );
}
}
class Cube extends Thread
{
int x; Cube(intn)
{
x = n;
}
public void run()
{
int cub = x * x * x;
System.out.println("Cube of " + x + " = " + cub );
}
}
class Number extends Thread
{
public void run()
{
Random random = new Random();
for(int i =0; i<10; i++)
{
int randomInteger = random.nextInt(100);
System.out.println("Random Integer generated : " + randomInteger);
Square s = new Square(randomInteger);
s.start();
Cube c = new Cube(randomInteger); c.start();
try
{
Thread.sleep(1000);
}
catch (InterruptedException ex)
{
System.out.println(ex);
}
}
}
}
public class multithread
{
public static void main(String args[])
{
Number n = new Number(); n.start();
}
}
Output:
Random Integer generated : 82
Square of 82 = 6724
Cube of 82 = 551368
Random Integer generated : 34
Square of 34 = 1156
Cube of 34 = 39304
Random Integer generated : 17
Square of 17 = 289
Cube of 17 = 4913
Result:
Thus, the Java program to implements multi-thread application has been executed successfully.
*****************************************************************
9. Write a threading program which uses the same method asynchronously to print the numbers 1 to 10
using Thread1 and to print 90 to 100 using Thread2.
Aim:
To write a Java threading program that implements same method asynchronously to print the
numbers 1 to 10 using Thread1 and to print 90 to 100 using Thread2.
Algorithm:
Step 1: Start the execution.
Step 2: Create first Thread to print 1 to 10
Step 3: Create second Thread to print 90 to 100
Step 4: Create a class constructor and class object and pass the arguments to Thread class.
Step 6: Use run() Method to execute the Thread.
Step 7: Display the result
Step 8: Stop the execution
Program:
public class NumberPrinter implements Runnable
{
private int start;
private int end;
public NumberPrinter(int start, int end)
{
this.start = start;
this.end = end;
}
@Override
Thread 2: 90
Thread 2: 91
Thread 1: 1
Thread 2: 92
Thread 1: 2
Thread 2: 93
Thread 2: 94
Thread 1: 3
Thread 2: 95
Thread 1: 4
Thread 2: 96
Thread 1: 5
Thread 2: 97
Thread 2: 98
Thread 1: 6
Thread 2: 99
Thread 1: 7
Thread 2: 100
Thread 1: 8
Thread 1: 9
Thread 1: 10
Result:
Thus, the Java program Java threading program that implements same method asynchronously to
print the numbers 1 to 10 using Thread1 and to print 90 to 100 using Thread2. has been executed
successfully.
*****************************************************************
10. Write a java 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
Aim:
To write a Java program to demonstrate the Arithmetic Exception, Number format Exception, Array
Index Out of Bound Exception, Negative Array Size Exception.
Algorithm:
Step 1: Start the execution.
Step 2: Create an ArithmeticException and then print ArithmeticException
Step 3: Create a NumberFormatException and then print NumberFormatException
Step 4: Create an ArrayIndexOutOfBoundException and then print ArrayIndexOutOfBoundException
Step 5: Create a NegativeArraySizeException and then print NegativeArraySizeException
Step 6: Display the result
Step 7: Stop the execution
Program:
public class ExceptionDemo
{
public static void main(String[] args)
{
// a) Arithmetic Exception
try
{
int result = 10 / 0; // Division by zero
}
catch (ArithmeticException e)
{
System.out.println("ArithmeticException caught: " + e.getMessage());
}
// b) NumberFormatException
try
{
String str = "abc";
int num = Integer.parseInt(str); // Trying to parse a non-numeric string
}
catch (NumberFormatException e)
{
System.out.println("NumberFormatException caught: " + e.getMessage());
}
// c) ArrayIndexOutOfBoundsException
try
{
int[] arr = new int[5];
arr[10] = 5; // Accessing an index beyond the size of the array
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBoundsException caught: " + e.getMessage());
}
// d) NegativeArraySizeException
try
{
int[] negativeArray = new int[-3]; // Creating an array with negative size
}
catch (NegativeArraySizeException e)
{
System.out.println("NegativeArraySizeException caught: " + e.getMessage());
}
}
}
Output:
Result:
Thus, the Java program Java program to demonstrate the Arithmetic Exception, Number
Exception, Array Index Out of Bound Exception, Negative Array Size Exception has been executed
successfully.
*****************************************************************
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?
Aim:
To write 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.
Algorithm:
Step 1: Start the execution.
Step 2: Read an input from the user to get the File Name with File Extension
Step 3: Create a File object and then use exists() to check whether the file exists or not.
Step 4: use canRead() method to check whether the file is readable.
Step 5: use canWrite() method to check whether the file is writable.
Step 6: use isDirectory() method to check whether the file is writable.
Step 7: use length() method to return the length of the file.
Step 8: Display the result
Step 9: Stop the execution
Program:
import java.io.*;
import javax.swing.*;
class FileDemo
{
public static void main(String args[])
{
String filename = JOptionPane.showInputDialog("Enter file name: ");
File f = new File(filename);
System.out.println("File exists: "+f.exists());
System.out.println("File is readable: "+f.canRead());
System.out.println("File is writable: "+f.canWrite());
System.out.println("Is a directory: "+f.isDirectory());
System.out.println("length of the file: "+f.length()+" bytes");
try
{
char ch;
StringBuffer buff = new StringBuffer("");
FileInputStream fis = new FileInputStream(filename);
while(fis.available()!=0)
{
ch = (char)fis.read();
buff.append(ch);
}
System.out.println("\nContents of the file are: ");
System.out.println(buff);
fis.close();
}
catch(FileNotFoundException e)
{
System.out.println("Cannot find the specified file...");
}
catch(IOException i)
{
System.out.println("Cannot read file...");
}
}
}
Output:
Result:
Thus, the Java program Java program to demonstrate various file() methods has been executed
successfully.
*****************************************************************
12. Write a program to accept a text and change its size and font. Include bold italic options. Use frames
and controls.
Aim:
To write Java program to accept a text and change its size, font and make the text bold and italic
using frames and controls.
Algorithm:
Step 1: Start the execution.
Step 2: import swing and awt package to create window based graphical applications
Step 3: Create JTextField to accept text from the user
Step 4: Create JComboBox to change various Font Style
Step 5: Create JCheckBox to make the text bold and italic
Step 6: Create JPanel to place the control in JPanel
Step 7: Display the result
Step 8: Stop the execution
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TextEditorApp extends JFrame
implements ActionListener {
private JTextField textField;
private JComboBox<String> fontSizeCombo,
fontNameCombo;
private JCheckBox boldCheckBox,
italicCheckBox;
public TextEditorApp() {
setTitle("Text Editor");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON
_CLOSE);
setLocationRelativeTo(null);
// Create main panel
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
// Create panel for text input
JPanel textPanel = new JPanel();
textPanel.setLayout(new FlowLayout());
JLabel label = new JLabel("Enter Text: ");
textField = new JTextField(20);
textPanel.add(label);
textPanel.add(textField);
// Create panel for font settings
JPanel fontPanel = new JPanel();
fontPanel.setLayout(new FlowLayout());
JLabel sizeLabel = new JLabel("Font Size:");
String[] sizes = {"12", "14", "16", "18", "20", "24",
"28", "32"};
fontSizeCombo = new JComboBox<>(sizes);
fontSizeCombo.addActionListener(this);
JLabel fontLabel = new JLabel("Font Name:");
String[] fonts =
GraphicsEnvironment.getLocalGraphicsEnvironme
nt().
getAvailableFontFamilyNames();
fontNameCombo = new JComboBox<>(fonts);
fontNameCombo.addActionListener(this);
boldCheckBox = new JCheckBox("Bold");
boldCheckBox.addActionListener(this);
italicCheckBox = new JCheckBox("Italic");
italicCheckBox.addActionListener(this);
fontPanel.add(sizeLabel);
fontPanel.add(fontSizeCombo);
fontPanel.add(fontLabel);
fontPanel.add(fontNameCombo);
fontPanel.add(boldCheckBox);
fontPanel.add(italicCheckBox);
// Add panels to main panel
mainPanel.add(textPanel, BorderLayout.NORTH);
mainPanel.add(fontPanel, BorderLayout.CENTER);
// Add main panel to frame
add(mainPanel);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == fontSizeCombo || e.getSource()
== fontNameCombo ||
e.getSource() == boldCheckBox || e.getSource() ==
italicCheckBox) {
updateFont();
}
}
private void updateFont() {
String text = textField.getText();
int size = Integer.parseInt((String)
fontSizeCombo.getSelectedItem());
String fontName = (String)
fontNameCombo.getSelectedItem();
int style = Font.PLAIN;
if (boldCheckBox.isSelected()) {
style += Font.BOLD;
}
if (italicCheckBox.isSelected()) {
style += Font.ITALIC;
}
Font font = new Font(fontName, style, size);
textField.setFont(font);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
TextEditorApp app = new TextEditorApp();
app.setVisible(true);
}
}
}
}
Output:
Result:
Thus, the Java program to accept a text and change its size, font and make the text bold and italic
using frames and controls has been executed successfully.
*****************************************************************
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).
Aim:
To write Java program to handle all mouse events and shows the event name at the center of the
window when a mouse event is fired.
Algorithm:
Step 1: Start the execution.
Step 2: import swing and awt package to create window based graphical applications
Step 3: Create JTextField to accept text from the user
Step 4: Create JComboBox to change various Font Style
Step 5: Create JCheckBox to make the text bold and italic
Step 6: Create JPanel to place the control in JPanel
Step 7: Display the result
Step 8: Stop the execution
Program:
import java.awt.*; import
java.awt.event.*;
class MouseDemo extends Frame implements MouseListener
{
String msg="";
MouseDemo()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent me)
{
msg="mouse clicked"; repaint();
}
public void mouseEntered(MouseEvent me)
{
msg="mouse entered";repaint();
}
public void mouseExited(MouseEvent me)
{
msg="mouse exited";repaint();
}
public void mousePressed(MouseEvent me)
{
msg="mouse pressed";repaint();
}
public void mouseReleased(MouseEvent me)
{
msg="mouse released";repaint();
}
public void paint(Graphics g)
{
g.drawString(msg,200,200);
}
}
class MouseEventsExample
{
public static void main(String arg[])
{
MouseDemo d=new MouseDemo(); d.setSize(400,400);
d.setVisible(true);
d.setTitle("Mouse Events Demo Program");
d.addWindowListener (new WindowAdapter()
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
}
}
Output:
Result:
Thus, the Java program to handle all mouse events and shows the event name at the center of the
window when a mouse event is fired has been executed successfully.
*****************************************************************
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.
Aim:
To write Java program to create simple calculator using grid layour and perfom arithmetic
operations and display the result.
Algorithm:
Step 1: Start the execution.
Step 2: import swing and awt package to create window based graphical applications
Step 3: Create JTextField to accept text from the user
Step 4: Create JComboBox to change various Font Style
Step 5: Create JCheckBox to make the text bold and italic
Step 6: Create JPanel to place the control in JPanel
Step 7: Display the result
Step 8: Stop the execution
Program:
// Java program to create a simple calculator
// with basic +, -, /, * using java swing elements
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
class Calculator extends JFrame implements ActionListener {
// create a frame
static JFrame f;
// create a textfield
static JTextField l;
// store oprerator and operands
String s0, s1, s2;
// default constrcutor
Calculator()
{
s0 = s1 = s2 = "";
}
// main function
public static void
main(String args[])
{
// create a frame
f = new JFrame("Swing
Calculator");
try {
// set look and feel
UIManager.setLookAndF
eel(UIManager.getSystem
LookAndFeelClassName(
));
}
catch (Exception e) {
System.err.println(e.getM
essage());
}
// create a object of class
Calculator c = new
Calculator();
// create a textfield
l = new JTextField(16);
// set the textfield to non
editable
l.setEditable(false);
// create number buttons
and some operators
JButton b0, b1, b2, b3, b4,
b5, b6, b7, b8, b9, ba, bs,
bd, bm, be, beq, beq1;
// create number buttons
b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");
// equals button
beq1 = new JButton("=");
// create operator buttons
// default constrcutor
Calculator()
{
s0 = s1 = s2 = "";
}
// main function
public static void main(String args[])
{
// create a frame
f = new JFrame("Swing Calculator");
try {
// set look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
System.err.println(e.getMessage());
}
// create a object of class
Calculator c = new Calculator();
// create a textfield
l = new JTextField(16);
// set the textfield to non editable
l.setEditable(false);
// create number buttons and some operators
JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, be, beq, beq1;
// create number buttons
b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");
// equals button
beq1 = new JButton("=");
// create operator buttons
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);
// set Background of panel
p.setBackground(Color.yellow);
// add panel to frame
f.add(p);
f.setSize(200, 220);
f.show();
}
public void actionPerformed(ActionEvent e)
{
String s = e.getActionCommand();
// if the value is a number
if ((s.charAt(0) >= '0' && s.charAt(0) <= '9') || s.charAt(0) ==
'.')
{
// if operand is present then add to second no
if (!s1.equals(""))
s2 = s2 + s;
else
s0 = s0 + s;
// set the value of text
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == 'C') {
// clear the one letter
s0 = s1 = s2 = "";
// set the value of text
l.setText(s0 + s1 + s2);
}
else if (s.charAt(0) == '=') {
double te;
// store the value in 1st
if (s1.equals("+"))
te = (Double.parseDouble(s0) + Double.parseDouble(s2));
else if (s1.equals("-"))
te = (Double.parseDouble(s0) - Double.parseDouble(s2));
else if (s1.equals("/"))
te = (Double.parseDouble(s0) / Double.parseDouble(s2));
else
te = (Double.parseDouble(s0) * Double.parseDouble(s2));
// convert it to string
s0 = Double.toString(te);
// place the operator
s1 = s;
// make the operand blank
s2 = "";
}
// set the value of text
l.setText(s0 + s1 + s2);
}
}
Output:
Result:
Thus, the Java program to create simple calculator using grid layour and perfom arithmetic
operations and display the result has been executed successfully.
*****************************************************************
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.
Aim:
To write Java program that simulates a traffic light which contains three lights red, yellow,green
when the user click the apporipriate message window must be displayed relevant messages.
Algorithm:
Step 1: Start the execution.
Step 2: Import swing and awt package to create window based graphical applications
Step 3: Create JLabel to display the message.
Step 4: Create JPanel to add the window components.
Step 5 Set the Font size and style to change the appearance of the message
Step 6: Create Three JRadioButton to display the red,yellow and green options.
Step 7: Display the result
Step 8: Stop the execution
Program:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class TrafficLightSimulator extends JFrame implements ItemListener {
JLabel lbl1, lbl2;
JPanel nPanel, cPanel;
CheckboxGroup cbg;
public TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setSize(600,400);
setLayout(new GridLayout(2, 1));
nPanel = new JPanel(new FlowLayout());
cPanel = new JPanel(new FlowLayout());
lbl1 = new JLabel();
Font font = new Font("Verdana", Font.BOLD, 70);
lbl1.setFont(font);
nPanel.add(lbl1);
add(nPanel);
Font fontR = new Font("Verdana", Font.BOLD, 20);
lbl2 = new JLabel("Select Lights");
lbl2.setFont(fontR);
cPanel.add(lbl2);
cbg = new CheckboxGroup();
Checkbox rbn1 = new Checkbox("Red Light", cbg, false);
rbn1.setBackground(Color.RED);
rbn1.setFont(fontR);
cPanel.add(rbn1);
rbn1.addItemListener(this);
Checkbox rbn2 = new Checkbox("Orange Light", cbg, false);
rbn2.setBackground(Color.ORANGE);
rbn2.setFont(fontR);
cPanel.add(rbn2);
rbn2.addItemListener(this);
Checkbox rbn3 = new Checkbox("Green Light", cbg, false);
rbn3.setBackground(Color.GREEN);
rbn3.setFont(fontR);
cPanel.add(rbn3);
rbn3.addItemListener(this);
add(cPanel);
setVisible(true);
// To close the main window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
// To read selected item
public void itemStateChanged(ItemEvent i) {
Checkbox chk = cbg.getSelectedCheckbox();
String str=chk.getLabel();
char choice=str.charAt(0);
switch (choice) {
case 'R':lbl1.setText("STOP");
lbl1.setForeground(Color.RED);
break;
case 'O':lbl1.setText("READY");
lbl1.setForeground(Color.ORANGE);
break;
case 'G':lbl1.setText("GO");
lbl1.setForeground(Color.GREEN);
break;
}
}
// main method
public static void main(String[] args) {
new TrafficLightSimulator();
}
}
Output
Result:
Thus, the Java program to simulates a traffic light which contains three lights red,yellow,green
when the user click the apporipriate message window must be displayed relevant messages has been
executed successfully.
*****************************************************************