Java Lab Manual
Java Lab Manual
Course Objectives:
● To write programs for solving real world problems using the java collection
framework.
Course Outcomes:
● Able to write programs for solving real world problems using the java collection
framework.
Note:
1. Use LINUX and MySQL for the Lab Experiments. Though not mandatory,
encourage the use
2. The list suggests the minimum program set. Hence, the concerned staff is
requested to add
1. Use Eclipse or Net bean platform and acquaint yourself with the various menus.
Create a test project,
add a test class, and run it. See how you can use auto suggestions, auto fill. Try
code formatter and
code refactoring like renaming variables, methods, and classes. Try debug step by
step with a small
program of about 10 to 15 lines which contains at least one if else condition and a
for loop.
2. 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 divided by zero.
B) Develop an applet in Java that receives an integer in one text field, and
computes its factorial
Value and returns it in another text field, when the button named “Compute” is
clicked.
4. Write a Java program that creates a user interface to perform integer divisions.
The user enters two
numbers in the text fields, Num1 and Num2. The division of Num1 and Num 2 is
displayed in the Result
field when the Divide button is clicked. If Num1 or Num2 were not an integer, the
program would throw
a Number Format Exception. If Num2 were Zero, the program would throw an
Arithmetic Exception.
5. Write a Java program that implements a multi-thread application that has three
threads. First thread
generates a random integer every 1 second and if the value is even, the 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.
7. Write a Java program that simulates a traffic light. The program lets the user
select one of three
“Stop” or “Ready” or “Go” should appear above the buttons in the selected color.
Initially, there is no
message shown.
8. Write a Java program to create an abstract class named Shape that contains two
integers and an
empty method named print Area (). Provide three classes named Rectangle,
Triangle, and Circle such
that each one of the classes extends the class Shape. Each one of the classes
contains only the method
the remaining lines correspond to rows in the table. The elements are separated by
commas.
Write a java program to display the table using Labels in Grid Layout.
10. Write a Java program that handles all mouse events and shows the event name
at the center of the
11. Write a Java program that loads names and phone numbers from a text file
where the data is
organized as one line per record and each field in a record are separated by a tab (\
t). It takes a
name or phone number as input and prints the corresponding other value from the
hash table (hint:
12. Write a Java program that correctly implements the producer – consumer
problem using the
13. Write a Java program to list all the files in a directory including the files
present in all its
subdirectories.
REFERENCE BOOKS:
1. Use Eclipse or Net bean platform and acquaint yourself with the various
menus. Create a test project, add a test class, and run it. See how you can use
auto suggestions, auto fill. Try code formatter and
code refactoring like renaming variables, methods, and classes. Try debug step
by step with a small program of about 10 to 15 lines which contains at least
one if else condition and a for loop.
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 divided by zero.
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="Calculator" width=300 height=300>
</applet>
*/
public class Calculator extends Applet implements ActionListener
{
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public void init( )
{
nPanel=new Panel();
T1=new TextField(30);
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++)
{
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");
clear=new Button("clear");
EQ=new Button("=");
T1.addActionListener(this);
for(int i=0;i<10;i++)
{
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);
SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++)
{
NumButtons[i].addActionListener(this);
}
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand ();
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+"))
{
num1=Integer.parseInt (T1.getText());
Operation='+';
T1.setText ("");
}
if(str.equals("-"))
{
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
}
if(str.equals("*"))
{
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
}
if(str.equals("/"))
{
num1=Integer.parseInt(T1.getText());
Operation='/';
T1.setText("");
}
if(str.equals("%"))
{
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
}
if(str.equals("="))
{
num2=Integer.parseInt(T1.getText());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e)
{
result=num2;
JOptionPane.showMessageDialog(this,"Divided by
zero");
}
break;
}
T1.setText(""+result);
}
if(str.equals("clear"))
{
T1.setText("");
}
}
}
OUTPUT:
JAVA Lab Program-3(a)
AIM:
PROGRAM:
import java.applet.Applet;
import java.awt.Graphics;
/*<applet code = "Hello" width = 400 height = 300>
</applet>*/
public class Hello extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello world",50,30);
}
}
OUTPUT:
JAVA Lab Program-3(b)
AIM:
Develop an applet in Java that receives an integer in one text field, and
computes its factorial Value and returns it in another text field, when the
button named “Compute” is clicked.
PROGRAM:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="Factorial" width=500 height=250>
</applet>*/
public class Factorial extends Applet implements ActionListener
{
Label L1,L2;
TextField T1,T2;
Button B1;
public void init()
{
L1=new Label("Enter any Number : ");
add(L1);
T1=new TextField(10);
add(T1);
L2=new Label("Factorial of Num : ");
add(L2);
T2=new TextField(10);
add(T2);
B1=new Button("Compute");
add(B1);
B1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==B1)
{
int value=Integer.parseInt(T1.getText());
int fact=factorial(value);
T2.setText(String.valueOf(fact));
}
}
int factorial(int n)
{
if(n==0)
return 1;
else
return n*factorial(n-1);
}
}
OUTPUT:
PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class A extends JFrame implements ActionListener
{
JLabel l1, l2, l3;
JTextField tf1, tf2, tf3; JButton b1;
A()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
l1 = new JLabel("Welcome");
setSize(800, 400);
l1 = new JLabel("Enter Number1");
add(l1);
tf1 = new JTextField(10);
add(tf1);
l2 = new JLabel("Enter Number2");
add(l2);
tf2 = new JTextField(10);
add(tf2);
l3 = new JLabel("Result");
add(l3);
tf3 = new JTextField(10);
add(tf3);
b1 = new JButton("Divide");
add(b1);
b1.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
try
{
int a = Integer.parseInt(tf1.getText());
int b = Integer.parseInt(tf2.getText());
if(b==0)
throw new ArithmeticException(" Divide by Zero Error"); float c = (float) a / b;
tf3.setText(String.valueOf(c));
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
catch (ArithmeticException ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
}
public class IntegerDivision
{
public static void main(String[] args)
{
A a = new A();
}
}
OUTPUT:
JAVA Lab Program-5
AIM:
PROGRAM:
import java.util.*;
class EvenNum implements Runnable
{
public int a;
public EvenNum(int a)
{
this.a = a;
}
public void run()
{
System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " +
a * a);
}
}
class OddNum implements Runnable
{
public int a;
public OddNum(int a)
{
this.a = a;
}
public void run()
{
System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a *
a * a);
}
}
class RandomNumGenerator extends Thread
{
public void run()
{
int n = 0;
Random rand = new Random();
try
{
for(int i = 0; i < 10; i++)
{
n = rand.nextInt(20);
System.out.println("Generated Number is " + n);
// check if random number is even or odd
if (n % 2 == 0)
{
Thread thread1 = new Thread(new EvenNum(n));
thread1.start();
}
else
{
Thread thread2 = new Thread(new OddNum(n));
thread2.start();
}
Thread.sleep(1000);
System.out.println("------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public class MultiThreadOddEven
{
public static void main(String[ ] args)
{
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}
OUTPUT:
Java Lab Program-6
AIM:
Write a Java program for the following:
a)Create a doubly linked list of elements.
b)Delete a given element from the above list.
c)Display the contents of the list after deletion.
PROGRAM:
import java.util.*;
public class DoubleLinkedListDemo
{
public static void main(String[ ] args)
{
int i,ch,element,position;
LinkedList<Integer> dblList = new LinkedList<Integer>();
System.out.println("1.Insert element at begining");
System.out.println("2.Insert element at end");
System.out.println("3.Insert element at position");
System.out.println("4.Delete a given element");
System.out.println("5.Display elements in the list");
System.out.println("6.Exit");
Scanner sc=new Scanner(System.in);
do
{
System.out.print("Choose your choice(1 - 6) :");
ch=sc.nextInt();
switch(ch)
{
case 1: System.out.print("Enter an element to insert
at begining : ");
element=sc.nextInt();
// to add element to doubly linked list at
begining
dblList.addFirst(element);
System.out.println("Successfully
Inserted");
break;
case 2: System.out.print("Enter an element to insert
at end : ");
element=sc.nextInt();
// to add element to doubly linked list at
end
dblList.addLast(element);
System.out.println("Successfully
Inserted");
break;
case 3: System.out.print("Enter position to insert
element : ");
position=sc.nextInt();
// checks if the position is lessthan or
equal to list size.
if(position<=dblList.size())
{
// To read element
System.out.print("Enter element : ");
element=sc.nextInt();
// to add element to doubly linked list at given
position
dblList.add(position,element);
System.out.println("Successfully
Inserted");
}
else
{
System.out.println("Enter the size between 0
to"+dblList.size());
}
break;
case 4: System.out.print("Enter element to remove :
");
Integer ele_rm;
ele_rm=sc.nextInt();
if (dblList.contains(ele_rm))
{
dblList.remove(ele_rm);
System.out.println("Successfully
Deleted");
Iterator itr=dblList.iterator();
System.out.println("Elements after
deleting :"+ele_rm);
while(itr.hasNext())
{
System.out.print(itr.next()+"<->");
}
System.out.println("NULL");
}
else
{
System.out.println("Element not found");
}
break;
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 selected
color. Initially, there is no message shown.
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());
PROGRAM:
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter
{
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}
public void mouseEntered(MouseEvent m)
{
adapterDemo.showStatus("Mouse Entered");
}
public void mouseExited(MouseEvent m)
{
adapterDemo.showStatus("Mouse Exited");
}
public void mouseClicked(MouseEvent m)
{
adapterDemo.showStatus("Mouse clicked");
}
public void mouseDragged(MouseEvent m)
{
adapterDemo.showStatus("Mouse dragged");
}
}
OUTPUT:
JAVA Lab Program-11
AIM:
Write a Java program that loads names and phone numbers from a text file
where the data is organized as one line per record and each field in a record
are separated by a tab (\t). It takes a name or phone number as input and
prints the corresponding other value from the hash table (hint: use hash
tables).
PROGRAM:
import java.io.*;
import java.util.*;
public class NamesAndPhoneNumbers
{
public static void main(String args[ ])
{
try
{
FileInputStream fis=new FileInputStream("phonefile.txt");
Scanner sc=new Scanner(fis).useDelimiter("\t");
Hashtable<String,String> ht=new Hashtable<String,String> ();
String[ ] strarray;
String a,str;
while(sc.hasNext())
{
a=sc.nextLine();
strarray=a.split("\t");
ht.put(strarray[0],strarray[1]);
System.out.println("hash table values are:\t"+strarray[0]+":---
>"+strarray[1]);
}
Scanner s=new Scanner(System.in);
System.out.println("Enter the name as given in the phone book");
str=s.next();
if(ht.containsKey(str))
{
System.out.println("phone no is"+ht.get(str));
}
else
{
System.out.println("Name is not matched");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
JAVA Lab Program-12
AIM:
Write a Java program that correctly implements the producer – consumer
problem using the concept of interthread communication.
PROGRAM:
class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
this.n=n;
valueSet=true;
System.out.println("Put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
try{
Thread.sleep(1000);
}
catch(Exception e){}
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q.get();
try{Thread.sleep(5000);}
catch(Exception e){}
}
}
}
class ProdCons
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-c to stop");
}
}
OUTPUT:
Write a Java program to list all the files in a directory including the files
present in all its subdirectories.
PROGRAM:
// Using directories.
import java.io.File;
class DirList
{
public static void main(String args[ ])
{
String dirname = "D:/gee-java/gee-JavaProgs";
File f1 = new File(dirname);
if (f1.isDirectory())
{
System.out.println("Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++)
{
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory())
{
System.out.println(s[i] + " is a directory");
}
else
{
System.out.println(s[i] + " is a file");
}
}
}
else
{
System.out.println(dirname + " is not a directory");
}
}
}
OUTPUT: