Java Lab Manual: Experimentos y Programas
Java Lab Manual: Experimentos y Programas
TECHNOLOGY
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
JAVA PROGRAMMING
LAB MANUAL
Regulation : R22
Academic Year : 2023-2024
II B. TECH II SEMESTER
CONTENTS
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
14 Write a Java program that implements Quick sort algorithm for sorting a list of
names in ascending order
15 Write a Java program that implements Bubble sort algorithm for sorting in
descending order and also shows the number of interchanges occurred for the
given set of integers.
Additional Programs
1. Use eclipse or Netbean platform and acquaint 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.
Program:-
public class Prog1
{
public static void main(String[] args)
{
System.out.println("\n Prog. is showing even no");
for(int i=2;i<=20;i++)
{
if(i%2==0)
{
System.out.print("\n "+i);
}
}
}
}
Output:-
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 divide by zero.
Program:-
Y
Import java.awt.*;
import java.awt.event.*;
Public class Calculator implements ActionListener
{
Int c,n;
String s1,s2,s3,s4,s5;
Frame f;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17;
Panel p;
TextField tf;
GridLayout g;
Calculator()
{
f = newFrame("My calculator");
p = newPanel();
f.setLayout(newFlowLayout());
b1 = newButton("0");
b1.addActionListener(this);
b2 = newButton("1");
b2.addActionListener(this);
b3 = newButton("2");
b3.addActionListener(this);
b4 = newButton("3");
b4.addActionListener(this);
b5 = newButton("4");
b5.addActionListener(this);
b6 = newButton("5");
b6.addActionListener(this);
b7 = newButton("6");
b7.addActionListener(this);
b8 = newButton("7");
b8.addActionListener(this);
b9 = newButton("8");
b9.addActionListener(this);
b10 = newButton("9");
b10.addActionListener(this);
b11 = newButton("+");
b11.addActionListener(this);
b12 = newButton("-");
b12.addActionListener(this);
b13 = newButton("*");
b13.addActionListener(this);
b14 = newButton("/");
b14.addActionListener(this);
b15 = newButton("%");
b15.addActionListener(this)
; b16 = newButton("=");
b16.addActionListener(this)
; b17 = new Button("C");
b17.addActionListener(this)
; tf = newTextField(20);
f.add(tf);
g = newGridLayout(4,4,10,20);
p.setLayout(g);
p.add(b1);p.add(b2);p.add(b3);p.add(b4);p.add(b5);p.add(b6);p.add(b7);p.add(b8);p.add(b9);
p.add(b10);p.add(b11);p.add(b12);p.add(b13);p.add(b14);p.add(b15);p.add(b16);p.add(b17);
f.add(p);
f.setSize(300,300);
f.setVisible(true);
}
Public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
s3 = tf.getText();
s4 = "0";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b2)
{
s3 = tf.getText();
s4 = "1";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b3)
{
s3 = tf.getText();
s4 = "2";
s5 = s3+s4;
tf.setText(s5);
}if(e.getSource()==b4)
{
s3 = tf.getText();
s4 = "3";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b5)
{
s3 = tf.getText();
s4 = "4";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b6)
{
s3 = tf.getText();
s4 = "5";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b7)
{
s3 = tf.getText();
s4 = "6";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b8)
{
s3 = tf.getText();
s4 = "7";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b9)
{
s3 = tf.getText();
s4 = "8";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b10)
{
s3 = tf.getText();
s4 = "9";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b11)
{
s1 = tf.getText();
tf.setText("");
c=1;
}
if(e.getSource()==b12)
{
s1 = tf.getText();
tf.setText("");
c=2;
}
if(e.getSource()==b13)
{
s1 = tf.getText();
tf.setText("");
c=3;
}
if(e.getSource()==b14)
{
s1 = tf.getText();
tf.setText("");
c=4;
}
if(e.getSource()==b15)
{
s1 = tf.getText();
tf.setText("");
c=5;
}
if(e.getSource()==b16)
{
s2 = tf.getText();
if(c==1)
{
n = Integer.parseInt(s1)+Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==2)
{
n = Integer.parseInt(s1)-Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==3)
{
n = Integer.parseInt(s1)*Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
if(c==4)
{
try
{
int p=Integer.parseInt(s2);
if(p!=0)
{
n = Integer.parseInt(s1)/Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
tf.setText("infinite");
}
catch(Exception i){}
}
if(c==5)
{
n = Integer.parseInt(s1)%Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
}
if(e.getSource()==b17)
{
tf.setText("");
}
}
publicstaticvoidmain(String[] abc)
{
Calculator v = newCalculator();
}
}
Output:-
3) a) Develop an applet that displays a simple message.
Program:-
java.applet.*;
Output:-
3.b) Develop an Applet that receives an integer in one text field & compute its factorial value
& returns it
in another text filed when the button “Compute” is clicked.
Program:-
java.lang.String; import
java.awt.event.*;
import java.applet.Applet;
Panel();
p.setLayout(new GridLayout());
TextField(20));
TextField(20));
add(b0=new Button("compute"));
b0.addActionListener(this);
int i,n,f=1;
n=Integer.parseInt(t1.getText());
for(i=1;i<=n;i++)
f=f*i;
t2.setText(String.valueOf(f)); repaint();
Output:-
4. Write a 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.
Program:-
import java.awt.*; import
java.awt.event.*; import
java.applet.*;
public class Add1 extends Applet implements ActionListener
{
String msg;
TextField num1, num2, res; Label l1, l2,
l3;
Button div; public void init()
{
l1 = new Label("Number 1"); l2 = new
Label("Number 2"); l3 = new
Label("result"); num1 = new
TextField(10); num2 = new
TextField(10); res = new TextField(30);
div = new Button("DIV");
div.addActionListener(this); add(l1);
add(num1); add(l2);
add(num2); add(l3);
add(res);
add(div);
}
APPLET.HTML
<html>
<head>
</head>
<body>
</applet>*/
</body>
</html>
Output:-
Kommuri Pratap Reddy Institute of Technology Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
5.) 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.
Program:-
import java.util.Random;
21
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
SquareThread(int randomNumbern)
{ number = randomNumbern;
}
CubeThread(int randomNumber)
{ number =
randomNumber;
}
Output:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
System.out.println();
}
// Base case
if (head == null || del == null)
{ return;
}
// Driver Code
public static void main(String[] args)
{
// Start with the empty list
DLL dll = new DLL();
Output:
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 selected color. Initially, there is no message
shown.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/*
* <applet code = "TrafficLightsExample" width = 1000 height = 500>
* </applet>
* */
redLight.addItemListener(this);
yellowLight.addItemListener(this);
greenLight.addItemListener(this);
add(redLight);
add(yellowLight);
Kommuri Pratap Reddy Institute of Technology Y
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
add(greenLight);
add(msg);
msg.setFont(new Font("Serif", Font.BOLD, 20));
}
public void itemStateChanged(ItemEvent ie) {
redLight.setForeground(Color.BLACK);
yellowLight.setForeground(Color.BLACK);
greenLight.setForeground(Color.BLACK);
if(redLight.getState() == true) {
redLight.setForeground(Color.RED);
msg.setForeground(Color.RED);
msg.setText("STOP");
}
else if(yellowLight.getState() == true) {
yellowLight.setForeground(Color.YELLOW);
msg.setForeground(Color.YELLOW);
msg.setText("READY");
}
else{
greenLight.setForeground(Color.GREEN);
msg.setForeground(Color.GREEN);
msg.setText("GO");
}
}
}
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
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 print Area () that prints the area of the given shape.
import java.util.*;
}
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
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.
Source code:
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
Output:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
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).
Source code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
{ mx = 30;
my = 60;
msg = "Mouse Released";
repaint();
}
repaint();
}
Output:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
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)
Source code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
}
}
36
Output:
12. Write a Java program that correctly implements the producer – consumer problem using the
concept of interthread communication.
Source Code:
class ItemQueue {
int item;
boolean valueSet = false;
{
while (!valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Consummed:" +
item); valueSet = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
notify();
return item;
}
ItemQueue itemQueue;
Consumer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
itemQueue.getItem();
}
}
}
class ProducerConsumer{
public static void main(String args[]) { ItemQueue itemQueue
= new ItemQueue(); new Producer(itemQueue);
new Consumer(itemQueue);
}
}
Output:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
13. Write a Java program to list all the files in a directory including the files present in all
its subdirectories.
Source Code:
import java.util.Scanner;
import java.io.*;
Output:
14. Write a Java program that implements Quick sort algorithm for sorting a list of names
in ascending Order.
Source Code:
{ String names[];
int length;
while (i <= j) {
while (this.names[i].compareToIgnoreCase(pivot) < 0) { i++;
}
if (i <= j) {
exchangeNames(i, j);
i++;
j--;
}
}
if (lowerIndex < j) {
quickSort(lowerIndex, j);
}
if (i < higherIndex) {
quickSort(i, higherIndex);
}
}
void exchangeNames(int i, int j)
{
String temp = this.names[i];
this.names[i] = this.names[j];
this.names[j] = temp;
}
Output:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
15. Write a Java program that implements Bubble sort algorithm for sorting in descending
order and also shows the number of interchanges occurred for the given set of integers.
Source Code:
import java.util.Scanner;
public class BubbleSort {
Output:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
Additional Programs
1. Write
a java program that connects to a database using JDBC
Aim:To Write a java program that connects to a database using
JDBC Source Code:
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{ Class.forName("com.mysql.jdbc.Driv
er");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/sonoo","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
2. Write
a java program to connect to a database using JDBC and insert values into it
Aim: To Write a java program to connect to a database using JDBC and insert values into it
Source Code:
import java.sql.*;
3. Write a java program to connect to a database using JDBC and delete values from it
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
Aim: To Write a java program to connect to a database using JDBC and delete values from it
Source Code:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
Output:
import java.awt.event.*;
import java.applet.*;
/*
</applet>
*/
addMouseListener(this);
addMouseMotionListener(this);
// save
coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse
clicked."; repaint();
// save
coordinates
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301
mouseX = 0;
mouseY = 10;
msg = "Mouse
entered."; repaint();
// save coordinates
mouseX = 0;
mouseY = 10;
msg = "Mouse
exited."; repaint();
// save coordinates
mouseX =
me.getX(); mouseY
= me.getY(); msg =
"Down"; repaint();
// save coordinates
mouseX =
me.getX(); mouseY
= me.getY(); msg =
"Up"; repaint();
// save coordinates
mouseX =
me.getX(); mouseY
= me.getY(); msg =
"*";
// show status
Output:
Kommuri Pratap Reddy Institute of Technology
(Approved by AICTE, New Delhi, Affiliated to JNTUH, Hyderabad)
Ghanpur (Village), Ghatkesar, TS-501301