Java Lab Manual
Java Lab Manual
(AUTONOMOUS)
B.Tech. in COMPUTER SCIENCE AND ENGINEERING
OOPS THROUGH JAVA LAB SYLLABUS (SDGI-R22 Regulations)
Course Objectives:
● To write programs using abstract classes.
● To write programs for solving real world problems using the java collection framework.
● To write multithreaded programs.
● To write GUI programs using swing controls in Java.
● To introduce java compiler and eclipse platform.
● To impart hands-on experience with java programming.
Course Outcomes:
● Able to write programs for solving real world problems using the java collection
framework.
● Able to write programs using abstract classes.
● Able to write multithreaded programs.
● Able to write GUI programs using swing controls in Java.
Note:
1. UseLINUXandMySQLfortheLabExperiments.Thoughnotmandatory,encouragethe
use of the Eclipse platform.
2. The list suggests them inimum program set. Hence, the on cerned staff is
requested to add more problems to the list as needed.
List of Experiments:
1.Use Eclipse or Netbean platform and acquaint ourself with the various menus. Create
atestproject,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 smallprogramofabout10to15lineswhich contains atleast one ifelse
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 Num2 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. Display the exception in a message dialog box.
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
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 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 printArea () that prints the area of the given shape.
9. Suppose that a table named Table.txt is stored in a textfile.The first line in the file is the
header, and 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 window when a mouse event is fired(Use Adapter classes).
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: use hash tables).
12. Write a Java program that correctly implements the producer – consumer problem
using the concept of inter thread communication.
13. Write a Java program to list all the files in a directory including the files
present in all its sub directories
15. Write a java program to store and retrieve data from database using JDBC..
REFERENCEBOOKS:
Aim: To create a test project, add a test class, and run it using Eclipse platform and acquaint
ourselves with the various menus. Observe how we can use auto suggestions, auto fill.
Procedure:
1. Set Up Eclipse
Download and install Eclipse IDE for Java Developers.
Launch Eclipse and choose a workspace (any folder).
2. Explore the Menus
Familiarize yourself with these menus:
File: New projects, classes, files
Edit: Refactor, format code, etc.
Source: Generate getters/setters, format, organize imports
Run: Run/debug your program
Window: Open different views like Console, Outline
Help: Eclipse documentation and updates
3. Create a Test Project and Class
1. Go to File → New → Java Project → Name it: TestProject
2. Right-click src folder → New → Class
3. Name it TestProgram and check the box for public static void main(String[] args).
7. Refactor Code
Aim: To create a simple calculator using grid layout to arrange buttons for the digits and
for the +, -,*, % operations.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorApp extends JFrame
{
private JTextField inputField;
private JButton[] numberButtons;
private JButton addButton, subtractButton, multiplyButton, divideButton, equalButton, clearButton;
private double firstNum, secondNum, result;
private char operator;
public CalculatorApp()
{
initializeUI();
initializeButtons();
addComponentsToFrame();
attachButtonListeners();
}
private void initializeUI()
{
setTitle("Simple Calculator");
setSize(300, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 4));
}
private void initializeButtons()
{
inputField = new JTextField();
inputField.setEditable(false);
inputField.setHorizontalAlignment(SwingConstants.RIGHT);
numberButtons = new JButton[10];
for (int i = 0; i < 10; i++)
{
numberButtons[i] = new JButton(String.valueOf(i));
}
addButton = new JButton("+");
subtractButton = new JButton("-");
multiplyButton = new JButton("*");
divideButton = new JButton("/");
equalButton = new JButton("=");
clearButton = new JButton("C");
}
private void addComponentsToFrame()
{
add(inputField);
for (int i = 1; i < 10; i++)
{
add(numberButtons[i]);
}
add(numberButtons[0]);
add(addButton);
add(subtractButton);
add(multiplyButton);
add(divideButton);
add(equalButton);
add(clearButton);
}
private void attachButtonListeners()
{
for (int i = 0; i < 10; i++)
{
int num = i;
numberButtons[i].addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
inputField.setText(inputField.getText() + num);
}
});
}
addButton.addActionListener(e -> setOperator('+'));
subtractButton.addActionListener(e -> setOperator('-'));
multiplyButton.addActionListener(e -> setOperator('*'));
divideButton.addActionListener(e -> setOperator('/'));
equalButton.addActionListener(e -> calculateResult());
clearButton.addActionListener(e ->
{
inputField.setText("");
firstNum = secondNum = result = 0;
operator = '\0';
});
}
}
}
Output:
3. A) Develop an applet in Java that displays a simple message.
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.
b)AIM:Develop an applet in Java that receives an integer in one textfield,and computes its factorial
value and returns it in another textfield,when the button named“Compute”is clicked.
Program:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="FactorialApplet" width=500 height=250>
</applet>*/
public class FactorialApplet 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:
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 Num2 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. Display the exception in a message dialog
box.
Aim: To Develop a Java program that creates a user interface to perform integer divisions.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
Output:
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.
Aim: To Develop a Java program that implements a multi-thread application that has three
threads
Program:
import java.util.*;
// class for Even Number
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 for Odd Number
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 to generate random number
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 wait for 1 second
Thread.sleep(1000);
System.out.println("------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
// Driver class
public class MultiThreadRandOddEven
{
public static void main(String[] args)
{
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}
Output:
6. Write a Java program for the following:
Aim:To Develop a java program to create a doubly linked list of elements and delete a
given elements from the above list and display the contents of the lis
Program:
import java.util.*;
public class DoublyLinkListDemo
{
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: // To read element form the user
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: // To read element form the user
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: // To read position form the user
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: // To read element form the user to remove
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;
Aim: To develop Java program to create an abstract class named Shape that contains
two integers and an empty method named print Area ().
Program:
import java.util.*;
abstract class Shape
{
public int x,y;
public abstract void printArea();
}
class Rectangle1 extends Shape
{
public void printArea()
{
float area;
area= x * y;
System.out.println("Area of Rectangle is " +area);
}
}
class Triangle extends Shape
{
public void printArea()
{
float area;
area= (x * y) / 2.0f;
System.out.println("Area of Triangle is " + area);
}
}
class Circle extends Shape
{
public void printArea()
{
float area;
area=(22 * x * x) / 7.0f;
System.out.println("Area of Circle is " + area);
}
}
public class AreaOfShapes
{
public static void main(String[] args)
{
int choice;
Scanner sc=new Scanner(System.in);
System.out.println("Menu \n 1.Area of Rectangle \n 2.Area of Traingle \n 3.Area
of Circle ");
System.out.print("Enter your choice : ");
choice=sc.nextInt();
switch(choice) {
case 1: System.out.println("Enter length and breadth for area of rectangle : ");
Rectangle1 r = new Rectangle1();
r.x=sc.nextInt();
r.y=sc.nextInt();
r.printArea();
break;
case 2: System.out.println("Enter bredth and height for area of traingle : ");
Triangle t = new Triangle();
t.x=sc.nextInt();
t.y=sc.nextInt();
t.printArea();
break;
case 3: System.out.println("Enter radius for area of circle : ");
Circle c = new Circle();
c.x = sc.nextInt();
c.printArea();
break;
default:System.out.println("Enter correct choice");
}
}
}
Output:
9. Suppose that a table named Table.txt is stored in a text file. The first line in the file is the
header, and 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.
Aim: To Develop A java program to display the table using Labels in Grid
LayoutSupposethatatablenamedTable.txtisstoredinatextfile.Thefirstlineinthefileisthehe
ader,and the remaining lines correspond to rows in the table. The elements are
separated by commas
Program:
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Text_To_Table extends JFrame
{
public void convertTexttotable()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
GridLayout g = new GridLayout(0, 4);
setLayout(g);
try
{
FileInputStream fis = new FileInputStream("table.txt");
Scanner sc = new Scanner(fis);
String[] arrayList;
String str;
while (sc.hasNextLine())
{
str = sc.nextLine();
arrayList = str.split(",");
for (String i : arrayList)
{
add(new Label(i));
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
setVisible(true);
setTitle("Display Data in Table");
}
}
public class TableText
{
public static void main(String[] args)
{
Text_To_Table tt = new Text_To_Table();
tt.convertTexttotable();
}
}
Text file:
Name,Age,Gender
Alice,22,Female
Bob,25,Male
Carol,23,Female
Output:
10.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 Develop 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).
Program:
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class MouseEventPerformer extends JFrame implements MouseListener
{
JLabel l1;
public MouseEventPerformer()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(new FlowLayout(FlowLayout.CENTER));
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
l1.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
l1.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
l1.setText("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
public static void main(String[] args) {
MouseEventPerformer mep = new MouseEventPerformer();
}
}
Output:
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: use hash tables).
Aim: To develop a Java program that loads names and phone numbers from a text file ,it
takes a name or phone number as input and prints the corresponding other value from the
hash table.
Program:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class PhoneBookApp
{
private static final String FILE_NAME = "data1.txt";
private static final String DELIMITER = "\t";
private static Map<String, String> phoneBook = new HashMap<>();
public static void main(String[] args)
{
loadContactsFromFile();
searchContact();
}
private static void loadContactsFromFile()
{
try (BufferedReader reader = new BufferedReader(new FileReader("data1.txt"))) {
String line;
while ((line = reader.readLine()) != null)
{
String[] parts = line.split(DELIMITER);
if (parts.length == 2)
{
String name = parts[0].trim();
String phoneNumber = parts[1].trim();
phoneBook.put(name, phoneNumber);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
class Buffer {
private final int maxSize;
private final Queue<Integer> buffer;
buffer.offer(value);
System.out.println("Produced: " + value);
notify(); // Notify consumer that data is available
}
@Override
public void run()
{
try
{
for (int i = 1; i <= 5; i++)
{
buffer.produce(i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
@Override
public void run()
{
try
{
for (int i = 0; i < 5; i++)
{
buffer.consume();
Thread.sleep(1500);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class ProducerConsumerApp
{
public static void main(String[] args)
{
Buffer buffer = new Buffer(3);
Producer producer = new Producer(buffer);
Consumer consumer = new Consumer(buffer);
producer.start();
consumer.start();
try
{
producer.join();
consumer.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
Output:
13. Write a Java program to list all the files in a directory including the files
present in all its sub directories
Aim: To develop a Java program to list all the files in a directory including the files
present in all its sub directories.
Program:
import java.io.File;
public class ListAllFiles
{
public static void main(String[] args)
{
// You can replace this with a dynamic input if needed
String directoryPath = "C:\\PRASHANTHI"; // Change this path