java cseab lab manual (2)
java cseab lab manual (2)
(UGC – AUTONOMOUS)
(Approved by AICTE, New Delhi & Affiliated to JNTUH, Hyderabad)
Accredited by *NBA, NAAC with ‘A+’ Grade, *nirf Ranked & an ISO Certified Institution
Narapally, Korremula Road, Ghatkesar, Medchal-Malkajgiri (Dist)-500 088
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
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:
Package Cse;
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:
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(b1 6);
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));
}
elsetf.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("");
}
}
public static void main(String[ ] args)
{
Calculator v = new Calculator();
}
}
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.
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;
n=Integer.parseInt(t1.getText());
for(i=1;i<=n;i++)
f=f*i;
t2.setText(String.valueOf(f));
repaint();
Output:
Program:-
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Add1 extends Applet implements ActionListener
{
String msg;
TextField num1, num2, res;
String s1 = num1.getText();
String s2 = num2.getText();
int num1 = Integer.parseInt(s1);
int num2 = Integer.parseInt(s2);
if (num2 == 0)
{
APPLET.HTML
<html>
<head>
</head>
<body>
/*<applet code="Add1.class"width=350 height=300>
</applet>*/
</body>
</html>
OUTPUT:
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.
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) {
SquareThreads Thread = new SquareThread(randomInteger);
sThread.start();
}
else {
CubeThread cThread = new CubeThread(randomInteger);
cThread.start();
}
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
System.out.println(ex);
}
}
}
}
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();
}
}
Output:
Or
package se;
import 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(int n)
{
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);
/*This thread generates random number 10 times
between 1 to 100 for every 1 second. The generated
random number is then passed as argument to
Square and Cube threads.
Output varies each time a program is executed.*/
}
}
}
public class Lab3 {
public static void main(String args[ ])
{
Number n = new Number();
n.start();
}
}
Output:
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.
Node(int d) {
data = d;
}}
public void push(int new_data) {
Node new_Node = new Node(new_data);
new_Node.next = head;
new_Node.prev = null;
if (head != null)
head.prev = new_Node;
head = new_Node;
}
if (del.next != null) {
del.next.prev = del.prev;
}
if (del.prev != null) {
del.prev.next = del.next;
}
return; }
public static void main(String[ ] args)
{
OUTPUT:
Original Linked list 10 8 4 2
Modified Linked list 8
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>
* */
add(redLight);
add(yellowLight);
add(greenLight);
add(msg);
Output:
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.
PROGRAM:
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() {
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\\eclipseworkspace\\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));
}
}
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>*/
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:
importjava.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 {
}
}
privateHashtable<String, String>readFromFile(String fileName) {
Hashtable<String, String>hashData = new Hashtable<String, String>();
try {
File f = new File("D:\\java\\" + fileName);
BufferedReaderbr = 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();
}
returnhashData;
}
}
Output:
Program:
classItemQueue {
int item;
booleanvalueSet = false;
synchronized intgetItem()
{
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
(InterruptedE
xception 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{
ItemQueueitemQueue;
Producer(ItemQueueitemQueue){
this.itemQueue = itemQueue; new
Thread(this, "Producer").start();
}
public void run() {
int i = 0; while(true) {
itemQueue.putItem(i++);
}
}
}
class Consumer implements Runnable{
ItemQueue itemQueue;
Consumer(ItemQueueitemQueue){
this.itemQueue = itemQueue; new
Thread(this, "Consumer").start();
}
public void run() { while(true)
{ itemQueue.getItem();
}
}
}
classProducerConsumer{
public static void main(String args[]) {
ItemQueueitemQueue
= new ItemQueue(); new Producer(itemQueue); new
Consumer(itemQueue);
}
}
Output:
13.Write a Java program to list all the files in a directory including the files
present in all its subdirectories.
Program:
importjava.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();
intlastIndex = path.lastIndexOf("\\");
14. Write a Java program that implements Quick sort algorithm for sorting a
list of names 41 in ascending Order.
Program:
public class QuickSortOnStrings { String names[];
int length;
public static void main(String[] args) {
QuickSortOnStringsobj = new
QuickSortOnStrings();
String stringsList[] = {""cse", "aiml", "ds", "se", "cs", "iot", "hello"};
obj.sort(stringsList);
for (String i : stringsList) {
System.out.print(i);
System.out.print(" ");
}
}
void sort(String array[]) {
if (array == null || array.length == 0) {
return;
}
this.names = array;
this.length = array.length;
quickSort(0, length - 1);
}
void quickSort(intlowerIndex, inthigherIndex) {
int i = lowerIndex; int j = higherIndex;
String pivot = this.names[lowerIndex + (higherIndex - lowerIndex) / 2];
while (i<= j) {
while (this.names[i].compareToIgnoreCase(pivot) < 0) {
i++;
}
while (this.names[j].compareToIgnoreCase(pivot) > 0) {
j--;
} 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)
{
this.names[i] = this.names[j];
this.names[j] = temp;
}
}
Output:
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.
Program:
importjava.util.Scanner;
public class BubbleSort {
public static void main(String[] args) {
Scanner read = new
Scanner(System.in);
int size, count = 0;
//Reading size of the list
System.out.print("Enter the list size: ");
size = read.nextInt(); //Creating list
with elements int list[] = new int[size];
System.out.println("Enter any " + size + " integer numbers: ");
for(inti = 0; i< size; i++)
list[i] = read.nextInt();