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

JAVA Lab Manual

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

JAVA Lab Manual

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 36

JAVA LAB MANUAL 2-1 CSE 2023

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:-

1
JAVA LAB MANUAL 2-1 CSE 2023

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:-

Importjava.awt.*;
importjava.awt.event.*;
publicclass Calculator implements ActionListener
{
intc,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;
TextFieldtf;
GridLayoutg;
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("/");

2
JAVA LAB MANUAL 2-1 CSE 2023

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);
}
publicvoidactionPerformed(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);
}
3
JAVA LAB MANUAL 2-1 CSE 2023

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)
{
4
JAVA LAB MANUAL 2-1 CSE 2023

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);

5
JAVA LAB MANUAL 2-1 CSE 2023

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();
}
}

6
JAVA LAB MANUAL 2-1 CSE 2023

Output:-

7
JAVA LAB MANUAL 2-1 CSE 2023

3) a) Develop an applet that displays a simple message.

Program:-

import java.awt.*; import

java.applet.*;

/*<applet code = “HelloJava” width = 200 height = 60 > </applet>*/

public class HelloJava extends Applet {

public void paint(Graphics g) {

g.drawString(“Hello Java”, 10, 100);


}
}

Output:-

8
JAVA LAB MANUAL 2-1 CSE 2023

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:-

import java.awt.*; import

java.lang.String; import

java.awt.event.*;

import java.applet.Applet;

public class Fact extends Applet implements ActionListener

String str; Button b0;

TextField t1,t2; Label

l1;

public void init(){ Panel p=new

Panel();

p.setLayout(new GridLayout());

add(new Label("Enter any Integer value"));

add(t1=new TextField(20));

add(new Label("Factorial value is: "));

add(t2=new TextField(20));

add(b0=new Button("compute"));

b0.addActionListener(this);

public void actionPerformed(ActionEvent e)

int i,n,f=1;
9
JAVA LAB MANUAL 2-1 CSE 2023

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

10
JAVA LAB MANUAL 2-1 CSE 2023

an integer, the program would throw a NumberFormatException. 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);
}

public void actionPerformed(ActionEvent ae)


{
String arg = ae.getActionCommand();
if (arg.equals("DIV"))
{
String s1 = num1.getText(); String s2
= num2.getText();
int num1 = Integer.parseInt(s1);

int num2 = Integer.parseInt(s2); if (num2


== 0)
{

11
JAVA LAB MANUAL 2-1 CSE 2023

msg = "Arithemetic Exception "; repaint();


}
else if ((num1 < 0) || (num2 < 0))
{
msg = "NumberFormat Exception"; repaint();
}
else
{
int num3 = num1 / num2; msg
= String.valueOf(num3);
}
res.setText(msg);
}
}
public void paint(Graphics g)
{
//g.drawString(msg, 30, 70);
}
}

APPLET.HTML

<html>

<head>

</head>

<body>

/*<applet code="Add1.class"width=350 height=300>

</applet>*/

</body>

</html>

Output:-

12
JAVA LAB MANUAL 2-1 CSE 2023

13
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;

class RandomNumberThread 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); if((randomInteger%2) == 0) {
SquareThread sThread = new SquareThread(randomInteger);
sThread.start();
}
else {
CubeThread cThread = new CubeThread(randomInteger);
cThread.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}

14
class SquareThread extends Thread {
int number;

SquareThread(int randomNumbern) {
number = randomNumbern;
}

public void run() {


System.out.println("Square of " + number + " = " + (number * number));
}
}

class CubeThread extends Thread {


int number;

CubeThread(int randomNumber) {
number = randomNumber;
}

public void run() {


System.out.println("Cube of " + number + " = " + number * number * number);
}
}

public class MultiThreadingTest {


public static void main(String args[]) {
RandomNumberThread rnThread = new RandomNumberThread();
rnThread.start();
}
}

15
Output:

16
6. Write a Java program for the following:
Create a doubly linked list of elements.
Delete a given element from the above
list.
Display the contents of the list after deletion.

// Java program to delete a node from


// Doubly Linked List

// Class for Doubly Linked


List public class DLL {
Node head; // head of list

/* Doubly Linked list


Node*/ class Node {
int data;
Node prev;
Node next;

// Constructor to create a new node


// next and prev is by default initialized
// as null
Node(int d) { data = d; }
}

// Adding a node at the front of the list


public void push(int new_data)
{
// 1. allocate node
// 2. put in the data
Node new_Node = new Node(new_data);

// 3. Make next of new node as head


// and previous as
NULL new_Node.next
= head; new_Node.prev
= null;

// 4. change prev of head node to new


node if (head != null)
head.prev = new_Node;

// 5. move the head to point to the new


node head = new_Node;
}

// This function prints contents of linked list


17
// starting from the given node
public void printlist(Node node)
{
Node last = null;

while (node != null) {


System.out.print(node.data + "
"); last = node;
node = node.next;
}

System.out.println();
}

// Function to delete a node in a Doubly Linked List.


// head_ref --> pointer to head node pointer.
// del --> data of node to be
deleted. void deleteNode(Node del)
{

// Base case
if (head == null || del == null)
{ return;
}

// If node to be deleted is head


node if (head == del) {
head = del.next;
}

// Change next only if node to be deleted


// is NOT the last
node if (del.next !=
null) {
del.next.prev = del.prev;
}

// Change prev only if node to be deleted


// is NOT the first
node if (del.prev !=
null) {
del.prev.next = del.next;
}

// Finally, free the memory occupied by del


return;
}

// Driver Code
public static void main(String[] args)
18
19
{
// Start with the empty
list DLL dll = new
DLL();

// Insert 2. So linked list becomes 2-


>NULL dll.push(2);

// Insert 4. So linked list becomes 4->2-


>NULL dll.push(4);

// Insert 8. So linked list becomes 8->4->2-


>NULL dll.push(8);

// Insert 10. So linked list becomes 10->8->4->2-


>NULL dll.push(10);

System.out.print("Created DLL is:


"); dll.printlist(dll.head);

// Deleting first node


dll.deleteNode(dll.head);

// List after deleting first node


// 8->4->2
System.out.print("\nList after deleting first node: ");
dll.printlist(dll.head);

// Deleting middle node from 8->4-


>2 dll.deleteNode(dll.head.next);

System.out.print("\nList after Deleting middle node: ");


dll.printlist(dll.head);
}
}

Output:

Original Linked list 10 8 4 2


Modified Linked list 8

20
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.

Program:-

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/*
* <applet code = "TrafficLightsExample" width = 1000 height = 500>
* </applet>
* */

public class TrafficLightsExample extends Applet implements ItemListener{

CheckboxGroup grp = new CheckboxGroup();


Checkbox redLight, yellowLight, greenLight;
Label msg;
public void init(){
redLight = new Checkbox("Red", grp, false);
yellowLight = new Checkbox("Yellow", grp, false);
greenLight = new Checkbox("Green", grp, false); msg
= new Label("");

redLight.addItemListener(this);
yellowLight.addItemListener(this);
greenLight.addItemListener(this);

add(redLight);
add(yellowLight);

21
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");
}
}
}

22
Output:-

23
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.*;

abstract class Shape {


int length, breadth, radius;

Scanner input = new Scanner(System.in);

abstract void printArea();

class Rectangle extends Shape


{ void printArea() {
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}
}

class Triangle extends Shape {


void printArea() {
System.out.println("\n*** Finding the Area of Triangle ***");
System.out.print("Enter Base And Height: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Triangle is: " + (length * breadth) / 2);
} 30

24
class Cricle extends Shape {
void printArea() {
System.out.println("\n*** Finding the Area of Cricle ***");

System.out.print("Enter Radius: ");


radius = input.nextInt();
System.out.println("The area of Cricle is: " + 3.14f * radius * radius);
}
}

public class AbstractClassExample {


public static void main(String[] args) {
Rectangle rec = new
Rectangle(); rec.printArea();

Triangle tri = new


Triangle(); tri.printArea();

Cricle cri = new


Cricle(); cri.printArea();
}
}

Output:

25
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.

Program:-

import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;

class A extends JFrame {


public A() {
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout g = new GridLayout(0, 3);
setLayout(g);
try {
FileInputStream fin = new
FileInputStream("C:\\Users\\User\\eclipse-workspace\\LabManual\\src\\HashTab.txt");
Scanner sc = new Scanner(fin).useDelimiter(",");
String[] arrayList;
String a;
while (sc.hasNextLine()) {
a = sc.nextLine(); arrayList =
a.split(","); for (String i : arrayList)
{
add(new JLabel(i));
}
}
} catch (Exception ex) {
}
setDefaultLookAndFeelDecorated(true);
32
pack();
setVisible(true);
}

26
}

27
public class TableTest {

public static void main(String[] args) {


A a = new A();
}
}

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).

Program:-

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

/*<applet code="MouseDemo" width=300 height=300>


</applet>*/
public class MouseDemo extends Applet implements MouseListener, MouseMotionListener { int mx = 0;
int my = 0;
String msg = "";

public void init() {


addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent me) {


mx = 20;
my = 40;
msg = "Mouse Clicked";
repaint();
}

28
public void mousePressed(MouseEvent me)
{ mx = 30;
my = 60;
msg = "Mouse Pressed";
repaint();
}

public void mouseReleased(MouseEvent me)

{
mx = 30;
my = 60;
msg = "Mouse Released";
repaint();
}

public void mouseEntered(MouseEvent me) {


mx = 40;
my = 80;
msg = "Mouse Entered";
repaint();
}

public void mouseExited(MouseEvent me) {


mx = 40;
my = 80;
msg = "Mouse Exited";
repaint();
}

public void mouseDragged(MouseEvent me) {


mx = me.getX();
my = me.getY();
showStatus("Currently mouse dragged" + mx + " " + my);

repaint();
}

public void mouseMoved(MouseEvent me) {


mx = me.getX();
my = me.getY();
showStatus("Currently mouse is at" + mx + " " + my); repaint();
}

public void paint(Graphics g) {


g.drawString("Handling Mouse Events", 30, 20);
g.drawString(msg, 60, 40);
}
}

29
Output:

30
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)

Program:-

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;

public class HashTab {


public static void main(String[] args) {
HashTab prog11 = new HashTab();
Hashtable<String, String> hashData = prog11.readFromFile("HashTab.txt");
System.out.println("File data into Hashtable:\n" + hashData); prog11.printTheData(hashData,
"raja"); prog11.printTheData(hashData, "123"); prog11.printTheData(hashData, "--- ");
}

private void printTheData(Hashtable<String, String> hashData, String input) { String output =


null;
if (hashData != null) {
Set<String> keys = hashData.keySet();
if (keys.contains(input)) {
output = hashData.get(input);
} else {
Iterator<String> iterator = keys.iterator(); while (iterator.hasNext())
{
String key = iterator.next();
String value = hashData.get(key);
if (value.equals(input)) {
output = key;
break;
}
}
}
}
System.out.println("Input given:" + input);
if (output != null) {
System.out.println("Data found in HashTable:" + output);
} else
{ System.out.println("Data not found in HashTable");

}
}
private Hashtable<String, String> readFromFile(String fileName)
{
Hashtable<String, String> hashData = new Hashtable<String, String>();
try
{

31
File f = new File("D:\\java\\" + fileName);
BufferedReader br = new BufferedReader(new
FileReader(f)); String line = null;
while ((line = br.readLine()) != null) {

String[] details = line.split("\t");


hashData.put(details[0], details[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return hashData;
}
}

Output:

32
12. Write a Java program that correctly implements the producer – consumer problem using
the concept of interthread communication.

Program:-
class ItemQueue {
int item;
boolean valueSet = false;

synchronized int getItem()

{
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;
}

synchronized void putItem(int item) {


while (valueSet)
try {
wait();
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.item = item;
valueSet = true;
System.out.println("Produced: " + item);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException caught");
}
notify();
}
}

class Producer implements Runnable{


ItemQueue itemQueue;
Producer(ItemQueue itemQueue){
this.itemQueue = itemQueue;
new Thread(this, "Producer").start();
}

33
public void run() {
int i = 0;
while(true) {
itemQueue.putItem(i++);
}
}
}
class Consumer implements Runnable{

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:

34
13. Write a Java program to list all the files in a directory including the files present in all
its subdirectories.

Program:-

import java.util.Scanner;
import java.io.*;

public class ListingFiles {

public static void main(String[] args) {

String path = null;


Scanner read = new Scanner(System.in);
System.out.print("Enter the root directory name: "); path =
read.next() + ":\\"; File f_ref = new File(path);
if (!f_ref.exists()) {
printLine();
System.out.println("Root directory does not exists!"); printLine();
}
else {
String ch = "y";
while (ch.equalsIgnoreCase("y")) {
printFiles(path);
System.out.print("Do you want to open any sub-directory(Y/N): ");
ch = read.next().toLowerCase();
if (ch.equalsIgnoreCase("y")) {
System.out.print("Enter the sub-directory name: "); path = path +
"\\\\" + read.next(); File f_ref_2 = new File(path);
if (!f_ref_2.exists()) {
printLine();
System.out.println("The sub-directory does not exists!");
printLine();
int lastIndex =
path.lastIndexOf("\\"); path =
path.substring(0, lastIndex);
}
}
}
}
System.out.println("***** Program Closed *****");
}
public static void printFiles(String path) {
System.out.println("Current Location: " +
path); File f_ref = new File(path);
File[] filesList = f_ref.listFiles();
for (File file : filesList) {
if (file.isFile())
System.out.println("- " + file.getName());
else

35
System.out.println("> " + file.getName());
}
}
public static void printLine() {
System.out.println("- -");
}
}

Output:

36

You might also like