You are on page 1of 34

JP LAB PROGRAMS

JAVA PROGRAMMING LAB (R18)


B.TECH II Year II Sem.

Department of Computer Science & Engineering


KAMALA INSTITUTE OF TECHNOLOGY & SCIENCE
SINGAPUR, HUZURABAD, KARIMNAGAR, TELANGANA - 505468
JP LAB PROGRAMS

R18 B.Tech. CSE Syllabus JNTU HYDERABAD


CS408PC: JAVA PROGRAMMING LAB
B.TECH II Year II Sem. LTPC
0021
Course Objectives:
 To write programs using abstract classes.
 To write programs for solving real world problems using java collection frame work.
 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 java collection frame work.
 Able to write programs using abstract classes.
 Able to write multithreaded programs.
 Able to write GUI programs using swing controls in Java.
Note:
1. Use LINUX and MySQL for the Lab Experiments. Though not mandatory, encourage the use
of Eclipse platform.
2. The list suggests the minimum program set. Hence, the concerned staff is requested to add
more problems to the list as needed.
List of Experiments:
1. Use Eclipse or Net bean 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.

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.

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.

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

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.
JP LAB PROGRAMS

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.

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.

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.

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 interthread communication.

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

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.

REFERENCE BOOKS
1. Java for Programmers, P. J. Deitel and H. M. Deitel, 10th Edition Pearson education.
2. Thinking in Java, Bruce Eckel, Pearson Education.
3. Java Programming, D. S. Malik and P. S. Nair, Cengage Learning.
4. Core Java, Volume 1, 9th edition, Cay S. Horstmann and G Cornell, Pearson.
JP LAB PROGRAMS

1. Use Eclipse or Net bean 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 forloop.

Program:
import java.util.Scanner; public class Lab1 {
static int i,n,b;

public static void main(String[]args){

for(i=0;i<2;i++) {
System.out.println(" ENTER THE NUMBER:");
Scanner obj=new Scanner(System.in);
n=obj.nextInt();

if (n % 2 == 0) {

System.out.println("the number " + n +"is even");


} else {

System.out.println("the number " + n + " is odd");


}

}
}
}

Output:

ENTER THE NUMBER:

520

the number 520 is even

ENTER THE NUMBER:

521

the number 521 is odd

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

Program:
JP LAB PROGRAMS

import java.awt.*;
import java.awt.event.*;
importjavax.swing.*;

public class CalcDemoextends JFrameimplements ActionListener {


JButtonn1, n2, n3, n4, n5, n6, n7, n8,n9,n0,pb, sb, mb, db, eb, ce;
JTextFieldt1;
JPaneljp1, jp2;
int num1, num2, ans;
String s, op,s1,s2,s3;

CalcDemo() {
super("MY Calc");
setSize(250, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
n1 = newJButton("1");
n2 = new JButton("2");
n3 = new JButton("3");
n4 = new JButton("4");
n5 = new JButton("5");
n6 = new JButton("6");
n7 = new JButton("7");
n8 = new JButton("8");
n9 = new JButton("9");
n0 = new JButton("0");
pb = new JButton("+");
sb = new JButton("-");
mb = new JButton("*");
db= new JButton("/"); eb
= newJButton("="); ce=
new JButton("CE"); t1 =
newJTextField(20);
jp1 = new JPanel(new FlowLayout());
jp1.add(t1);

jp2 = new JPanel(new GridLayout(0, 4, 5, 5));

jp2.add(n7);
jp2.add(n8);
jp2.add(n9);
jp2.add(mb);

jp2.add(n4);
jp2.add(n5);
jp2.add(n6);
jp2.add(sb);

jp2.add(n1);
jp2.add(n2);
jp2.add(n3);
jp2.add(pb);

jp2.add(db);
jp2.add(n0);
jp2.add(ce);
jp2.add(eb);

setLayout(new FlowLayout());
JP LAB PROGRAMS

add(jp1);
add(jp2);

num1 =0;
num2 =0;
ans= 0;

n0.addActionListener(this);
n1.addActionListener(this);
n2.addActionListener(this);
n3.addActionListener(this);
n4.addActionListener(this);
n5.addActionListener(this);
n6.addActionListener(this);
n7.addActionListener(this);
n8.addActionListener(this);
n9.addActionListener(this);

pb.addActionListener(this);
sb.addActionListener(this);
mb.addActionListener(this);
db.addActionListener(this);
eb.addActionListener(this);
ce.addActionListener(this);

setVisible(true);
}

public void actionPerformed(ActionEvent obj) {


s = obj.getActionCommand();
s1= t1.getText();
if (s == "1" || s == "2" || s == "3" || s == "4"||s == "5" || s ==
"6" || s == "7" || s == "8"||s == "9" || s == "0")
{
t1.setText(t1.getText() + s);//showing result in text box
}
else if (s == "CE")
t1.setText("");
else if (s == "+" || s == "-" || s == "*" || s == "/") {
if (!t1.getText().equals("")) {
num1 = Integer.parseInt(t1.getText());//1st string is
stored in num1
op = s;//operator is stored in op
s2=s1+"";//1st string and operator is stored in s2
t1.setText("");//printing only operator
}
}else if (s == "=") {
if (!t1.getText().equals("")) {
s3=t1.getText();
num2 = Integer.parseInt(t1.getText());
if (op.equals("+")) {
ans= num1 +num2;
} else if (op.equals("-")) {
ans= num1 -num2;
} else if (op.equals("*")) {
ans= num1 *num2;
} else if (op.equals("/")) {
ans= num1 /num2;
}
JP LAB PROGRAMS

t1.setText(s2+op+s3+"="+ ans);
}
}

}
public static void main (String[]args){
// TODO Auto-generated method stub
new CalcDemo();

Output:
JP LAB PROGRAMS

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

Program:
import java.awt.*;
import java.applet.*;
public class Lab3a extends Applet {
public void paint(Graphics g){

g.drawString("ADITHYA",200,200);

}
}

OUTPUT:

3b) 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.applet.*;
import java.awt.*;
importjava.awt.event.*;
import java.util.Scanner;

public class LabthreeBextends Applet implements ActionListener {


TextFieldt1,t2;//2 textboxesdeclaration
Label l1,l2;
Button b1,b2;

public void init(){


t1=newTextField(10);
JP LAB PROGRAMS

t2=new TextField(10);
l1=new Label("enter Integer");
l2=new Label("Factorial");
b1=new Button("Compute");
b2=new Button("Cancel");
//intialisation of obj finished

//adding
add(l1);
add(t1);
add(b1);
add(l2);
add(t2);
add(b2);

b1.addActionListener(this);// registering
b2.addActionListener(this);

}
public void actionPerformed(ActionEvent obj){

if(obj.getActionCommand()=="Compute") {
String s = t1.getText();//get Text will give txt from box

//t2.setText(s);//posting into txtbox2(copied from txtbox1)


Scanner in = new Scanner(s);
if (in.hasNextInt()) {
int a = in.nextInt();
int b = 1;
for (int i = 1; i<= a; i++)
b = b * i;

t2.setText("" + b);
} else
t2.setText("enter integers only");
}
else if(obj.getActionCommand()=="Cancel"){
t1.setText("");
t2.setText("");

}
}

}
JP LAB PROGRAMS

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 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. Display the exception in a message dialogbox.

Program:
package labprograms;

import java.applet.*;
import java.awt.*;
importjava.awt.event.*;
import java.util.Scanner;
import javax.swing.*;
public class LabFourextends Applet implements ActionListener {
TextFieldt1, t2,t3;
Label l1, l2, l3;
Button b1, b2;

public void init() {


t1 = new TextField(10);
t2 = new TextField(10);
t3 = new TextField(10);
l1 = new Label("Number 1");
l2 = new Label("Number 2");
l3 = new Label("Answer");
b1 = new Button("Divide");
b2 = newButton("Clear");

add(l1);
add(t1);

add(l2);
add(t2);
add(b1);
JP LAB PROGRAMS

add(l3);
add(t3);

add(b2);

b1.addActionListener(this);
b2.addActionListener(this);

public void actionPerformed(ActionEvent obj) {


int a, b, c;
if (obj.getActionCommand() == "Divide") {
try {
a = Integer.parseInt(t1.getText());
b = Integer.parseInt(t2.getText());
c = a / b;
t3.setText("" + c);
} catch (ArithmeticException e) {
JOptionPane.showMessageDialog(null, "Arithmectic Exception"
+ e);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Exception" + e);
}
} else if (obj.getActionCommand() == "Clear") {
t1.setText("");
t2.setText("");
t3.setText("");
}

}
}
// WE CAN WRITE IN THIS WAY ALSO TO REDUCE PROGRAMSIZE
/*
if (obj.getActionCommand() == "Divide") {
try{
a=Integer.parseInt(t1.getText());
b=Integer.parseInt(t2.getText());
c=a/b;
t3.setText(""+c);
}
catch(ArithmeticException e){
JoptionPane.showMessageDialog(null,"arthimeticException"+e);
}
catch(NumberFormatException e){
JoptionPane.showMessageDialog(null,"Exception"+e);
}
}
*/

Output:
JP LAB PROGRAMS

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

Program:
package labprograms;

import java.util.Random;

class Mythread1 implements Runnable{


Threadt;
Random r;//kneed to import random package
Mythread2 t2;

Mythread1(){
t=new Thread(this,"Mythread1");
r=new Random();
t.start();
}
public void run(){
//a random integer we have to generate
t2=new Mythread2();
while(true) {
try{

int x=r.nextInt(100);
System.out.println("Mythread1:"+x);
if(x%2==0){
t2.num=x;
t2.bt2=true;
notifyAll();
}

Thread.sleep(1000);
} catch (Exception e){

}
}
}
}
class Mythread2 implements Runnable{
JP LAB PROGRAMS

Thread t;
int num;
booleanbt2;
Mythread2(){
t=new Thread(this,"Mythread2");
bt2=false;
t.start();
}
public void run(){
//a random integer we have to generate
while(true){
while (!bt2) {
try {
wait();
} catch (Exception e) {

}
}

System.out.println("Mythread2:" + num * num);


bt2=false;

// Thread.sleep(1000);

}
}
}

public class Lab5 {


public static void main(String[] args){
new Mythread1();
}

Output:

Mythread1:99

Mythread1:67

Mythread1:13

Mythread1:12

Mythread1:69

Mythread2:144

Mythread1:64

Mythread2:4096

Mythread1:53

Mythread1:42

Mythread2:1764

Mythread1:95
JP LAB PROGRAMS

Mythread1:78

Mythread2:6084

Mythread1:58

Mythread2:3364

Mythread1:24

Mythread2:576

Mythread1:32

Mythread2:1024

Mythread1:71

Mythread1:55

Process finished with exit code -1

6. Write a Java program for the following: Create a doubly linked list of elements. Delete a given
element from the above list.R18 B.Tech. CSE Syllabus JNTU HYDERABAD 62 Display the contents of
the list afterdeletion.
import java.util.Scanner;

class DNode{
int data;
DNodell,rl;
DNode(int data){
this.data=data;
ll=null;
rl=null;
}
}

class DNodeDemo{//class for doing operations

Scanner in=new Scanner(System.in);


DNodehead;
DNodeDemo(){
head=null;
}

void addNode(int data){


DNode p=new DNode(data);
DNodet=head;
if(head==null){// if it is a starting node then head will point
first node
head=p;
}
else{

while (t.rl!=null){
t=t.rl;
}
t.rl=p;
p.ll=t;
}
JP LAB PROGRAMS

void delete(){
DNode t=head;
DNodetbefore=t;
while (t.rl!=null){
tbefore=t;
t=t.rl;
}
System.out.print(tbefore.data+"<=>");
System.out.print(t.data+"<=>");

tbefore.rl=null;
t.ll=null;

t=head;
tbefore=t;
while (t.rl!=null){
tbefore=t;
t=t.rl;
}
System.out.print(tbefore.data+"<=>");
System.out.print(t.data+"<=>");

}
void delNode(){
DNode t=head;
display();
System.out.println("enter the node no to delete");
int n=in.nextInt();
int p=1;
if(n<1)
System.out.println("not possible to delete ");
else
{
if(n==1){
head=head.rl;
head.ll=null;

}
else if(n>1) {
while (t != null && p < n) {
t = t.rl;
p++;
}
if (p == n &&t!=null) {
(t.ll).rl= t.rl;
if (t.rl!= null)
(t.rl).ll= t.ll;

}
else{
System.out.println("NO node at position:"+n);
}

}
}
}
JP LAB PROGRAMS

void display(){
DNode t=head;
int c=0;
if(t==null){
System.out.println("Dlist is empty");
}
else{
System.out.print("<=>");
while (t!=null){
System.out.print(t.data+"<=>");
t=t.rl;
c++;
}
System.out.println("null");
System.out.println("no of nodes:"+c);
System.out.println();
}
}

public class Lab6 {


public static void main(String[] args){
DNodeDemo p=new DNodeDemo();
Scanner in=new Scanner(System.in);
int ch;
while(true){
System.out.println("**MENU**");
System.out.println("1.Add node");
System.out.println("2.DEl node");
System.out.println("3.Print nodes");
System.out.println("4.exit");
System.out.println("enter your choice");
ch=in.nextInt();
switch(ch){
case1:
System.out.println("enter your data of node:");
int d=in.nextInt();
p.addNode(d);
break;
case 2:p.delNode();
break;
case 3:p.display();
break;
case 4:System.exit(0);
}
}
}
}

OUTPUT:

**MENU**

1.Add node

2.DEl node

3.Print nodes
JP LAB PROGRAMS

4.exit

enter your choice

Dlist is empty

**MENU**

1.Add node

2.DEl node

3.Print nodes

4.exit

enter your choice

enter your data of node:

**MENU**

1.Add node

2.DEl node

3.Print nodes

4.exit

enter your choice

enter your data of node:

**MENU**

1.Add node

2.DEl node

3.Print nodes

4.exit

enter your choice

enter your data of node:

6
JP LAB PROGRAMS

**MENU**

1.Add node

2.DEl node

3.Print nodes

4.exit

enter your choice

<=>2<=>4<=>6<=>null
no of nodes:3

enter the node no to delete

NO node at position:4

**MENU**

1.Add node

2.DEl node

3.Print nodes

4.exit

enter your choice

2
<=>2<=>4<=>6<=>null

no of nodes:3

enter the node no to delete

**MENU**

1.Add node

2.DEl node

3.Print nodes

4.exit

enter your choice


JP LAB PROGRAMS

<=>2<=>6<=>null

no of nodes:2

**MENU**

1.Add node

2.DEl node

3.Print nodes

4.exit

enter your choice

Process finished with exit code 0

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.*;
import java.awt.*;
importjava.awt.event.*;
public class Lab7 extends Applet implements ItemListener {

Checkbox c1,c2,c3;
CheckboxGroupcg;
public void init(){
cg=new CheckboxGroup();
c1=new Checkbox("Red",cg,false);
c2=new Checkbox("Yellow",cg,false);
c3=new Checkbox("Green",cg,false);

add(c1);
add(c2);
add(c3);

c1.addItemListener(this);
c2.addItemListener(this);
c3.addItemListener(this);
}

public void paint(Graphics g){


String s="";
g.drawOval(100,100, 40,40);
g.drawOval(100,150, 40,40);
g.drawOval(100,200, 40, 40);
if(cg.getSelectedCheckbox().getLabel()=="Red"){
JP LAB PROGRAMS

s="STOP";
g.setColor(Color.RED);g.fill
Oval(100,100, 40, 40);
g.drawString(s, 150, 120);
}

else if(cg.getSelectedCheckbox().getLabel()=="Yellow"){
s="READY";
g.setColor(Color.YELLOW);g.f
illOval(100,150, 40, 40);
g.drawString(s, 150, 170);
}
else if(cg.getSelectedCheckbox().getLabel()=="Green"){
s="GO";
g.setColor(Color.GREEN);g.fi
llOval(100,200, 40, 40);
g.drawString(s, 150, 220);
}

public void itemStateChanged(ItemEvent obj){


repaint();

Output:
JP LAB PROGRAMS

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

Program:
abstract class Shape{
abstract void Area();
int a=6,b=21;
}
class Rectangle1 extends Shape{
intarea;
void Area(){
area=a*b;
System.out.println("Area of rectangle: " +area);
}
}
class Triangle1 extends Shape{
intarea;
void Area(){
area=a*b/2;
System.out.println("Area of triangle: " +area);
}
}
class Circle extends Shape{
doublearea;
voidArea(){
area=3.14*a*a;
System.out.println("Area of circle: " +area);
}
}
class Lab8 {
JP LAB PROGRAMS

public static void main(String[] args) {


// TODO Auto-generated method stub
Rectangle1 obj=new Rectangle1();
obj.Area();
Triangle1 obj1=new Triangle1();
obj.Area();
Circle obj2=new Circle();
obj2.Area();
}

OutPut:

Area of rectangle: 126

Area of rectangle: 126

Area of circle: 113.03999999999999

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

Program:
package labprograms;

import javax.swing.*;
import java.awt.*;
import java.io.FileReader;
import java.util.Scanner;
import java.util.StringTokenizer;

public class Lab9 extends JFrame{


JPaneljp;
Lab9(){
super("Lab9");
setSize(500,500);
setLayout(new FlowLayout());
jp=new JPanel();
jp.setLayout(new GridLayout(4,3));
try{

FileReader fin=new FileReader("adi1.txt");

Scanner in=new Scanner(fin);


int x;
//System.out.println("enter input using spaces");

while(in.hasNext()){

String z=in.next();
StringTokenizerst=new StringTokenizer(z,",");
while(st.hasMoreTokens()){
JP LAB PROGRAMS

//System.out.println(st.nextToken());
jp.add(new JLabel(st.nextToken()));
}

}
}catch(Exception e){}
add(jp);
setVisible(true);
}
public static void main (String[]args){
// TODO Auto-generated method stub
new Lab9();

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

Program:
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
import java.lang.String;
public class MouseDemoextends Applet implements MouseListener{
Stringstr;
public void init() {
str="";
addMouseListener(this);
}
public void paint(Graphics g) {
g.drawString(str, 100, 100);
JP LAB PROGRAMS

public void mousePressed(MouseEvent obj) {


str="MousePressed";
repaint();
}
public void mouseReleased(MouseEvent obj) {
str="MouseReleased";
repaint();
}
public void mouseClicked(MouseEvent obj) {
str="MouseClicked";
repaint();
}
public void mouseEntered(MouseEvent obj) {
str="MouseEntered";
repaint();
}
public void mouseExited(MouseEvent obj) {
str="MouseExited";
repaint();
}
}

Output:
JP LAB PROGRAMS

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

Program:
JP LAB PROGRAMS

import java.io.*;
import java.util.*;
public class Lab11 {

public static void main(String[] args)throws Exception {


// TODO Auto-generated method stub
FileReader fin=new FileReader("phonebook.txt");

Scanner in=new Scanner(fin);


Hashtable<String,String>ht=new Hashtable<String,String>();

while(in.hasNext()){

String z=in.nextLine();

StringTokenizerst=new StringTokenizer(z,"\t");
while(st.hasMoreTokens()){
//System.out.println(st.nextToken());
ht.put(st.nextToken(), st.nextToken());
}

Scanner in1=new Scanner(System.in);


int ch;
while(true){
System.out.println("**MENU**");
System.out.println("1.Search Phone no with name ");
System.out.println("2.Search Name no with phone");
System.out.println("3.Print all ");
System.out.println("4.exit ");
System.out.println("enter Your choice:");
ch=in1.nextInt();
switch(ch){
case 1: System.out.println("Enter the name to find phone no:");
String s=in1.next();
if(ht.containsKey(s))
System.out.println("The phone no of "+s+" is: "+
ht.get(s));
else
System.out.println("No name exists in the list");
break;
case 2: System.out.println("Enter the Phone to find name:");
String p=in1.next();

if(ht.contains(p)){
for(Map.Entry<String, String> e:ht.entrySet()){
if(p.equals(e.getValue())){
System.out.println("The Name is "+e.getKey()+" with
phone: "+p);
}
}
}
else
System.out.println("No Phone no exists in the list");

break;
case 3:
JP LAB PROGRAMS

for(Map.Entry<String, String> e:ht.entrySet()){

System.out.println("The Name is "+e.getKey()+" with


phone: "+e.getValue());

}
break;
case 4:System.exit(0);
}

Output:

**MENU**

1.Search Phone no with name

2.Search Name no with phone

3.Print all

4.exit

enter Your choice:

Enter the name to fine phone no:

adithya

The phone no of adithya is: 9391583281

**MENU**

1.Search Phone no with name

2.Search Name no with phone

3.Print all

4.exit

enter Your choice:

Enter the Phone to fine name:

2837264829

The Name is ghi with phone: 2837264829


JP LAB PROGRAMS

**MENU**

1.Search Phone no with name

2.Search Name no with phone

3.Print all

4.exit

enter Your choice:

The Name is abc with phone: 9147382747

The Name is def with phone: 2837481934

The Name is ghi with phone: 2837264829

The Name is adithya with phone: 9391583281

**MENU**

1.Search Phone no with name

2.Search Name no with phone

3.Print all

4.exit

enter Your choice:

Process finished with exit code 0

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

Program:
class Q {
int n;
booleanvalueSet= false;
synchronized int get() {
while(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet= false;
notify();
return n;
JP LAB PROGRAMS

}
synchronized void put(int n) {
while(valueSet)
try { wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n= n;
valueSet= true;
System.out.println("Put: " + n);
notify();
}
}
class Producer implements Runnable {
Qq;
Producer(Q q) {
this.q= q;
new Thread(this, "Producer").start();
}
public void run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Qq;
Consumer(Q q) {
this.q= q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
classProducerConsumer
{
public static void main(String args[]) { Q
q = newQ();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

Output:

Got:26163

Put:26164

Got:26164

Put:26165

Got:26165
JP LAB PROGRAMS

Put:26166

Got:26166

Put:26167

Got:26167

Put:26168

Got:26168

Put:26169

Got:26169

Put:26170

Got:26170

Put:26171

Got:26171

Put:26172

Got:26172

Put:26173

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

Program:
import java.io.*;
public class SubDirectories {

public static void filedisp(File d) {


File arr[]=d.listFiles();

for(File x:arr) {
if(x.isFile())
System.out.println("FIle: "+x);
if(x.isDirectory()) {
System.out.println("Dir: "+x);
filedisp(x);
}

public static void main(String[] args)throws Exception {


// TODO Auto-generated method stub

File d=new File("F:\\521\\II-2 Class notes\\Java by raghu sir");


JP LAB PROGRAMS

//String s[]=d.list();

if(d.exists()&&d.isDirectory())
filedisp(d);

Output:

Dir: F:\521\II-2 Class notes\Java by raghu sir\1ST

FIle: F:\521\II-2 Class notes\Java by raghu sir\1ST\12april.txt

FIle: F:\521\II-2 Class notes\Java by raghu sir\1ST\dailyclass.txt

FIle: F:\521\II-2 Class notes\Java by raghu sir\1ST\jp4.txt

FIle: F:\521\II-2 Class notes\Java by raghu sir\1ST\jp5.txt

FIle: F:\521\II-2 Class notes\Java by raghu sir\1ST\OOP viewing world book.pdf

FIle: F:\521\II-2 Class notes\Java by raghu sir\1ST\Screenshot 2021-04-06 103715.png

FIle: F:\521\II-2 Class notes\Java by raghu sir\1ST\String class methods.docx

Dir: F:\521\II-2 Class notes\Java by raghu sir\2ND

FIle: F:\521\II-2 Class notes\Java by raghu sir\2ND\interface10may.pdf

FIle: F:\521\II-2 Class notes\Java by raghu sir\2ND\Packages and interfaces.pdf

Dir: F:\521\II-2 Class notes\Java by raghu sir\2ND\randomaccessfile link

FIle: F:\521\II-2 Class notes\Java by raghu sir\2ND\randomaccessfile


link\httpsdocs.oracle.comjavase7docsapijavaioRandomAccessFile.html#mode.txt

FIle: F:\521\II-2 Class notes\Java by raghu sir\2ND\sql.pdf

14. Write a Java program that implements Quick sort algorithm for sorting a list of names in
ascendingorder

Program:
class Qsort{
String a[];
Qsort(String x[]){
a=x;
}
public void qsortfun(int l,intr) {

if(l<r) {
intp=l;

int i=l;
intj=r;
JP LAB PROGRAMS

System.out.println("array positions p i,j are


p="+p+",i="+i+",j="+j);

while(i<j){

while(a[p].compareTo(a[i])>=0&&i<r) {
i++;
System.out.println("i="+i);
}
while(a[p].compareTo(a[j])<0&&j>l) {
j--;
System.out.println("j="+j);
}

if(i<j) {
System.out.println("swapingi,j,i="+i+",j="+j);
String t=a[i];
a[i]=a[j];
a[j]=t;

}
}

System.out.println("found pivot pos and


swapingpivot,j,p="+p+",j="+j);
String t=a[p];
a[p]=a[j];
a[j]=t;
//divide
if(l<j)
qsortfun(l,j-1);

if(j+1<r)
qsortfun(j+1,r);

}
}
public void disp() {
for(String x:a)
System.out.print(" "+x);
System.out.println("");
}
}
public class Quicksort {

public static void main(String[] args) {


// TODO Auto-generated method stub
String x[]= {"peddi","adithya","vardhan","reddy"};
Qsort q=new Qsort(x);
System.out.println("\nbefore sort");
q.disp();
q.qsortfun(0,x.length-
1);System.out.println("\nafter
sort");q.disp();
}

Output:
JP LAB PROGRAMS

before sort

peddi adithya vardhan reddy

array positions p i,j are p=0,i=0,j=3

i=1

i=2

j=2

j=1

found pivot pos and swapingpivot,j,p=0,j=1

array positions p i,j are p=2,i=2,j=3

i=3

found pivot pos and swapingpivot,j,p=2,j=3

after sort

adithya peddireddy vardhan

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

Program:
import java.util.*;
import java.lang.reflect.Array;
import java.util.Arrays;

class exam2<T extends Comparable<? super T>>{


T[] a;
int n;
exam2(T[] x){
a=x;
}
void sort() {
T temp;
int count=0;
for(int i=0;i<a.length;i++) {
for(int j=0;j<a.length-1;j++) {
if(a[j].compareTo(a[j+1])<0) {
count++;
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("The number of Interchanges="+count);

}
JP LAB PROGRAMS

void print() {
for(T i:a) {
System.out.println(i);
}
}
}

public class BubblebyGeneric {


public static void main(String args[]) {

Integer a[]= {2,9,7,6,4,1};


exam2<Integer> obj1=new exam2<Integer>(a);
System.out.println("before sorting");
obj1.print();
obj1.sort();
System.out.println("after sorting");
obj1.print();

Output:

before sorting

The number of Interchanges=4

after sorting

You might also like