Java Programming Lab Manual
Java Programming Lab Manual
Java Programming Lab Manual
II-B.TECH II SEMESTER
1
JAVA PROGRAMMING LAB MLRITM
CERTIFICATE
2
JAVA PROGRAMMING LAB MLRITM
PREFACE
This “JAVA PROGRAMMING” lab manual is intended to teach the basic Java Applications
and Java Applets. Readers of this manual must be familiar with the basic syntax of C or C++ and
Object Oriented features. Java is increasingly becoming the default choice of the IT industry
especially industries involved in software development at system level. Therefore, for proper
development of Java Applications among the students, this practical lab manual has been
prepared. The manual contains the exercise programs and their solution for easy & quick
understanding of the students. We hope that this practical manual will be helpful for students of
CSE for understanding the subject from the point of view of applied aspects. There is always
scope for improvement in the manual. We would appreciate to receive valuable suggestions from
readers and users for future use.
By,
SIVA RAMA PRASAD KOLLU.
3
JAVA PROGRAMMING LAB MLRITM
ACKNOWLEDGEMENT
It was really a good experience , working with “JAVA PROGRAMMING” . First we would
like to thank Mr.K.Abdul Basith, Assoc.Professor, HOD of Department of Computer Science
and Engineering, Marri Laxman Reddy Institute of technology & Management for his concern
and giving the technical support in preparing the document. We are deeply indebted and
gratefully acknowledge the constant support and valuable patronage of Dr.R.Kotaih, Director,
Marri Laxman Reddy Institute of technology & Management for giving us this wonderful
opportunity for preparing the “JAVA PROGRAMMING” laboratory manual. We express our
hearty thanks to Dr.K.Venkateswara Reddy, Principal, Marri Laxman Reddy Institute of
technology & Management, for timely corrections and scholarly guidance. At last, but not the
least I would like to thanks the entire CSE and IT Department faculties those who had inspired
and helped us to achieve our goal.
By,
SIVA RAMA PRASAD KOLLU.
4
JAVA PROGRAMMING LAB MLRITM
VISION
To be as an ideal academic institution by graduating talented engineers to be ethically strong,
competent with quality research and technologies.
MISSION
To fulfill the promised vision through the following strategic characteristics and aspirations:
Utilize rigorous educational experiences to produce talented engineers.
Create an atmosphere that facilitates the success of students.
Programs that integrate global awareness, communication skills and Leadership qualities.
Education and Research partnership with institutions and industries to prepare the
students for interdisciplinary research.
5
JAVA PROGRAMMING LAB MLRITM
VISION
To empower the students to be technologically adept, innovative, self-motivated and responsible
global citizen possessing human values and contribute significantly towards high quality
technical education with ever changing world.
MISSION
6
JAVA PROGRAMMING LAB MLRITM
The Programme Educational Objectives (PEOs) that are formulated for the CSE programme are
listed below:
7
JAVA PROGRAMMING LAB MLRITM
The Program Outcomes (POs) of the department are defined in a way that the Graduate
Attributes are included, which can be seen in the Program Outcomes (POs) defined.
8
JAVA PROGRAMMING LAB MLRITM
COURSE STRUCTURE:
COURSE OBJECTIVES:
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.
9
JAVA PROGRAMMING LAB MLRITM
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. Write a Java Program to
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:
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).
10
JAVA PROGRAMMING LAB MLRITM
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.
11
JAVA PROGRAMMING LAB MLRITM
Week-1
Aim: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.
Program:
class Fact
{
public static void main(String[] args)
{
int number = 5;
int factorial = number;
for(int i =(number - 1); i > 1; i--)
{
factorial = factorial * i;
}
System.out.println("Factorial of a number is:" + factorial);
}
}
12
JAVA PROGRAMMING LAB MLRITM
Program:
import java.util.Scanner;
public class Fibonacci
{
public static void main(String[] args)
{
int n, a = 0, b = 0, c = 1;
Scanner s = new Scanner(System.in);
System.out.print("Enter value of n:");
n = s.nextInt();
System.out.print("Fibonacci Series:");
for(int i = 1; i <= n; i++)
{
a = b;
b = c;
c = a + b;
System.out.print(a+" ");
}
}
}
Output:
13
JAVA PROGRAMMING LAB MLRITM
Aim :Write a java program to find whether the give number is Armstrong number or not.
Program:
import java.io.*;
import java.util.*;
class ArmStrong
{
public static void main(String[] args)throws IOException
{
int t,s=0,n,r;
System.out.println("Enter number:");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
n=Integer.parseInt(br.readLine());
t=n;
while( t!=0)
{
r=t%10;
s=s+r*r*r;
t=t/10;
}
if(n==s)
System.out.println("Number given is Armstrong");
else
System.out.println("Number given is not Armstrong");
}
}
Output:
Enter number:153
Number given is Armstrong
14
JAVA PROGRAMMING LAB MLRITM
Program:
import java.io.*;
import java.util.*;
class RevStr
{
public static void main(String[] args) throws IOException
{
String or, rev="";
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter String:");
or=dis.readLine();
int len=or.length();
for(int i=len-1;i>=0;i--)
{
rev=rev+or.charAt(i);
}
System.out.println("Reverse of a string:"+rev);
}
}
Output:
Enter String:siva
Reverse of a string:avis
15
JAVA PROGRAMMING LAB MLRITM
Output:
Enter a value:
4
Enter b value:
6
Enter c value:
-2
THE REAL SOLUTIONS ARE X=0.28077640640441515 Y==-1.7807764064044151
16
JAVA PROGRAMMING LAB MLRITM
Aim :Write a java program to print Fibonacci series for the given number using recursion
Program:
import java.io.*;
public class FibRec
{
static int fib(int i)
{
if(i==1||i==2)
{
return i-1;
}
else
{
return fib(i-1)+fib(i-2);
}
}
17
JAVA PROGRAMMING LAB MLRITM
Aim: Write a java program to print Fibonacci series for the given number using non-recursion
Program:
import java.io.*;
class FibNonRec
{
public static void main(String args[])throws IOException
{
BufferedReader br;
int a=0;
int b=1,t,n;
br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter n value:");
n=Integer.parseInt(br.readLine());
System.out.print("FIBONACCI SEQENCE IS:");
System.out.print(a+"\t");
do
{
System.out.print(b+"\t");
t=b;
b=a+b;
a=t;
}while(b<=n);
}
}
Output:
enter n value:
5
FIBNOCCI SEQUENCE IS: 0 1 1 2 3 5
18
JAVA PROGRAMMING LAB MLRITM
19
JAVA PROGRAMMING LAB MLRITM
Aim: Write a java program to check the given string is palindrome or not
Program:
import java.io.*;
public class Palindrome
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String:");
String str=br.readLine();
char ch[]=new char[str.length()];
for(int i=str.length()-1,j=0;i>=0;i--,j++)
ch[j]=str.charAt(i);
String restr=new String(ch);
System.out.println("Reverse of String "+str+" is "+restr);
if(str.compareTo(restr)==0)
System.out.println(str+" "+"is a Palindrome");
else
System.out.println(str+" "+"is not a Palindrome");
}
}
Output:
Enter String:
madam
Reverse of String madam is madam
madam is a Palindrome
20
JAVA PROGRAMMING LAB MLRITM
Aim: Write a java program to print the prime numbers upto nth number
Program:
import java.io.*;
class Primenos
{
public static void main(String args[])throws IOException
{
BufferedReader br;
int i,t,flag,n;
br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("ENTER n VALUE:");
n=Integer.parseInt(br.readLine());
System.out.println("PRIME NUMBERS UP TO"+" "+n+":");
for(i=2;i<=n;i++)
{
flag=1;
for(t=2;t<i;t++)
{
if(i%t==0)
{
flag=0;
break;
}
}
if(flag==1)
System.out.println(i);
}
}
}
Output:
ENTER n VALUE:
5
PRIME NUMBERS UP TO 5:
2
3
5
21
JAVA PROGRAMMING LAB MLRITM
Aim: To read a line of integers and display each integer and sum of all integers
Program:
import java.util.*;
import java.io.*;
class StrTok
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String in numbers");
String str=br.readLine();
StringTokenizer s=new StringTokenizer(str);
int x,sum=0;
while(s.hasMoreTokens())
{
String str1=s.nextToken();
x=Integer.parseInt(str1);
System.out.println(x);
sum+=x;
}
System.out.println("total sum:"+sum);
}
}
Output:
Enter String in numbers
385
3
8
5
total sum: 16
22
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
1. What do you know about Java?
2. What are the supported platforms by Java Programming Language?
3. List any five features of Java?
4. Why is Java Architectural Neutral?
5. How Java enabled High Performance?
6. Why Java is considered dynamic?
7. What is Java Virtual Machine and how it is considered in context of Java’s platform
independent feature?
8. List any two Java IDE’s?
9. List some of the Java keywords.
10. What do you mean by Object?
11. Define class?
12. What kind of variables a class can consist of?
13. What is a Local Variable?
14. What is a Instance Variable?
15. What is a Class Variable?
16. What is the default value of byte datatype in Java?
17. What is the default value of float and double datatype in Java?
18. When a byte datatype is used?
19. What is a static variable?
20. When parseInt() method can be used?
21. Define Inheritance?
22. What is Polymorphism?
23. What is Abstraction?
24. What is Encapsulation?
25. What is the primary benefit of Encapsulation?
26. Explain the following line used under Java Program
public static void main (String args[ ])
27. Define JRE i.e. Java Runtime Environment?
28. Define JIT compiler?
29. What is the difference between object oriented programming language and object based
programming language?
30. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
31. What is the difference between static and non-static variables?
32. What is the difference between a break statement and a continue statement?
33. What is the purpose of the System class?
34. List primitive Java types?
35. Which arithmetic operations can result in the throwing of an ArithmeticException?
36. Variable of the boolean type is automatically initialized as?
37. What will happen if static modifier is removed from the signature of the main method?
38. What is the default value of an object reference declared as an instance variable?
39. What is dot operator?
23
JAVA PROGRAMMING LAB MLRITM
24
JAVA PROGRAMMING LAB MLRITM
Week 2:
Aim: 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.
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code=" Calculator" width=500 height=500>
</applet>
*/
25
JAVA PROGRAMMING LAB MLRITM
}
add(add);
add(sub);
add(mul);
add(div);
add(mod);
add(clear);
add(EQ);
for(int i=0;i<10;i++)
{
b[i].addActionListener(this);
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
26
JAVA PROGRAMMING LAB MLRITM
{
v1=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("%"))
{
v1=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("="))
{
v2=Integer.parseInt(t1.getText());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
t1.setText(""+result);
}
if(str.equals("clear"))
{
t1.setText("");
}
}
}
27
JAVA PROGRAMMING LAB MLRITM
Output:
28
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
1. What is the difference between an Applet and a Java Application ?
2. How to create a TextField?
3. How to create a Label?
4. How to create a Button?
5. To which package Applet class belongs to?
6. What is the use of ActionLitstener?
7. Write the syntax of applet tag.
8. List out some of the classes of awt package.
9. List out the methods of Applet class.
10. what is the use of init() method in an applet?
11. How to set background of an applet?
12. List out some colors of Color class.
13. What is meant by GridLayout?
14. How to set layout for an aplet?
15. Where does actionPerformed() method is present?
16. What is meant by thos keyword?
17. Write the syntax for creation of Button.
18. How to set name for a button?
19. How to set name for a label?
20. How to set length of the text field?
21. What is method used to add the listener for a component?
22. How to add components to the applet?
23. What is method used to remove the listener for a component?
24. Write the syntax of actionPerformed() method.
25. What is the use of getActionCommand() method?
26. What is the return type of charAt() method?
27. Write the syntax of charAt() method.
28. In which package Character class is present?
29. What is the use of isDigit() method?
30. What is the syntax of getText() method?
31. What is the syntax of setText() method?
32. How to use equals() method?
33. What is the return type of equals() method?
34. To which class equals() method belongs to?
35. What is the use of parseInt() method?
36. What is the super class of all the applets?
37. How to set number of rows and columns in GridLayout?
38. Where does event subpackage present?
39. what do you mean by </> in applet tag?
40. What are the methods of ActionListener?
41. What is access specifier for actionPerformed() method?
42. Why public is access specifer for actionPerformed() method?
29
JAVA PROGRAMMING LAB MLRITM
30
JAVA PROGRAMMING LAB MLRITM
Week 3
Program:
import java.applet.*;
import java.awt.*;
/*
<applet code="SimpleApplet" height=300 width=300>
</applet>
*/
public class SimpleApplet extends Applet
{
public void paint(Graphics g)
{
g.setColor(Color.black);
setBackground(Color.yellow);
g.drawString("HI APPLET PROGRAM",80,150);
}
}
Output:
31
JAVA PROGRAMMING LAB MLRITM
b) Aim: To develop an applet in java that receives an integer in one text field and computes its
factorial in value and returns it in another text field ,when the button named “Compute” is
clicked.
Program:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*<applet code=Fact width=500 height=500>
</applet>*/
public class Fact extends Applet implements ActionListener
{
Button b1,b2;
Label l1,l2;
TextField tf1,tf2;
public void init()
{
b1=new Button("COMPUTE");
b1.addActionListener(this);
b2=new Button("CLEAR");
b2.addActionListener(this);
tf1=new TextField(20);
tf2=new TextField(20);
l1=new Label("NUMBER");
l2=new Label("RESULT");
// setLayout(new GridLayout(3,2));
add(l1);
add(tf1);
add(l2);
add(tf2);
add(b1);
add(b2);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
int a=Integer.parseInt(tf1.getText());
int fact=1;
for(int i=1;i<=a;i++)
fact*=i;
tf2.setText(""+fact);
}
else
{
tf1.setText("");
32
JAVA PROGRAMMING LAB MLRITM
tf2.setText("");
}
}
}
Output:
33
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
34
JAVA PROGRAMMING LAB MLRITM
38. How many ways exist to display messages to the user in applets?
39. What is the tag used to embed an applet in HTML file?
40. What is the importance of applets in Java coding?
41. How will you initialize an applet?
42. What is the order of method invocation in an applet?
43. What is the sequence for calling the methods by AWT for applets?
44. What tags are mandatory when creating HTML to display an applet?
45. Which method is used to output a string to an applet?
46. Is drawstring() method overloaded?
47. To which method drawstring () method belongs to?
48. To which class setBackground() method belongs to?
49. What is an Applet ?
50. What happens when an applet is loaded ?
35
JAVA PROGRAMMING LAB MLRITM
Week-4
Aim:Write a Java program that creates a user interface to perform integer divisions. The user
enters two numbers in the text fields, Num1 andNum2. 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.applet.*;
import java.awt.*;
import java.awt.event.*;
36
JAVA PROGRAMMING LAB MLRITM
catch(ArithmeticException ex)
{
tf3.setText("--");
SampleDialog d=new SampleDialog(this,"EXCEPTION","DIVIDE BY ZERO");
d.setVisible(true);
}
catch(Exception ex)
{
37
JAVA PROGRAMMING LAB MLRITM
tf1.setText("");
tf2.setText("");
tf3.setText("");
}
}
Output:
38
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
39
JAVA PROGRAMMING LAB MLRITM
40
JAVA PROGRAMMING LAB MLRITM
Week-5
Aim: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.*;
class Even implements Runnable
{
public int x;
public Even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN and Square of " + x + " is: " +
x * x);
}
}
class Odd implements Runnable
{
public int x;
public Odd(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x *
x * x);
}
}
class A extends Thread
{
public void run()
{
int num = 0;
Random r = new Random();
try
{
for (int i = 0; i < 5; i++)
{
41
JAVA PROGRAMMING LAB MLRITM
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " +
num);
if (num % 2 == 0)
{
Thread t1 = new Thread(new Even(num));
t1.start();
}
else
{
Thread t2 = new Thread(new Odd(num)); t2.start();
}
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public class ThreeThreadDemo
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
}
Output:
42
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
43
JAVA PROGRAMMING LAB MLRITM
44
JAVA PROGRAMMING LAB MLRITM
Week-6
Program:
import java.util.Scanner;
/* Class Node */
class Node
{
protected int data;
protected Node next, prev;
/* Constructor */
public Node()
{
next = null;
prev = null;
data = 0;
}
/* Constructor */
public Node(int d, Node n, Node p)
{
data = d;
next = n;
prev = p;
}
/* Function to set link to next node */
public void setLinkNext(Node n)
{
next = n;
}
/* Function to set link to previous node */
public void setLinkPrev(Node p)
{
prev = p;
}
/* Funtion to get link to next node */
public Node getLinkNext()
{
return next;
}
/* Function to get link to previous node */
45
JAVA PROGRAMMING LAB MLRITM
/* Class linkedList */
class linkedList
{
protected Node start;
protected Node end ;
public int size;
/* Constructor */
public linkedList()
{
start = null;
end = null;
size = 0;
}
/* Function to check if list is empty */
public boolean isEmpty()
{
return start == null;
}
/* Function to get size of list */
public int getSize()
{
return size;
}
/* Function to insert element at begining */
public void insertAtStart(int val)
{
Node nptr = new Node(val, null, null);
if(start == null)
46
JAVA PROGRAMMING LAB MLRITM
{
start = nptr;
end = start;
}
else
{
start.setLinkPrev(nptr);
nptr.setLinkNext(start);
start = nptr;
}
size++;
}
/* Function to insert element at end */
public void insertAtEnd(int val)
{
Node nptr = new Node(val, null, null);
if(start == null)
{
start = nptr;
end = start;
}
else
{
nptr.setLinkPrev(end);
end.setLinkNext(nptr);
end = nptr;
}
size++;
}
/* Function to insert element at position */
public void insertAtPos(int val , int pos)
{
Node nptr = new Node(val, null, null);
if (pos == 1)
{
insertAtStart(val);
return;
}
Node ptr = start;
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node tmp = ptr.getLinkNext();
ptr.setLinkNext(nptr);
47
JAVA PROGRAMMING LAB MLRITM
nptr.setLinkPrev(ptr);
nptr.setLinkNext(tmp);
tmp.setLinkPrev(nptr);
}
ptr = ptr.getLinkNext();
}
size++ ;
}
/* Function to delete node at position */
public void deleteAtPos(int pos)
{
if (pos == 1)
{
if (size == 1)
{
start = null;
end = null;
size = 0;
return;
}
start = start.getLinkNext();
start.setLinkPrev(null);
size--;
return ;
}
if (pos == size)
{
end = end.getLinkPrev();
end.setLinkNext(null);
size-- ;
}
Node ptr = start.getLinkNext();
for (int i = 2; i <= size; i++)
{
if (i == pos)
{
Node p = ptr.getLinkPrev();
Node n = ptr.getLinkNext();
p.setLinkNext(n);
n.setLinkPrev(p);
size-- ;
return;
}
ptr = ptr.getLinkNext();
}
}
48
JAVA PROGRAMMING LAB MLRITM
{
System.out.println("\nDoubly Linked List Operations\n");
System.out.println("1. insert at begining");
System.out.println("2. insert at end");
System.out.println("3. insert at position");
System.out.println("4. delete at position");
System.out.println("5. check empty");
System.out.println("6. get size");
49
JAVA PROGRAMMING LAB MLRITM
50
JAVA PROGRAMMING LAB MLRITM
Output:
51
JAVA PROGRAMMING LAB MLRITM
52
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
53
JAVA PROGRAMMING LAB MLRITM
43. How can we pass argument to a function by reference instead of pass by value?
44. How an object is serialized in java?
45. When we should use serialization?
46. Is it compulsory for a Try Block to be followed by a Catch Block in Java for Exception
handling?
47. Is there any way to skip Finally block of exception even if some exception occurs in the
exception block?
48. When the constructor of a class is invoked?
49. Can we override static methods of a class?
50. How garbage collection is done in Java?
54
JAVA PROGRAMMING LAB MLRITM
Week-7
Aim: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.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<applet code="Traffic.class" width=400 height=400></applet>*/
CheckboxGroup cbg;
Checkbox red, yellow,green;
String msg=" ";
public void init ()
{
cbg=new CheckboxGroup();
red=new Checkbox("RED",cbg,true);
yellow=new Checkbox("YELLOW",cbg,true);
green=new Checkbox("GREEN",cbg,true);
add(red);
add(yellow);
add(green);
red.addItemListener(this);
yellow.addItemListener(this);
green.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
if (ie.getSource () == red)
colourNum = 1;
else if (ie.getSource () == yellow)
colourNum = 2;
else
colourNum = 3;
repaint ();
55
JAVA PROGRAMMING LAB MLRITM
public void paint (Graphics g) // responsible for graphics "within" the window
{
g.setColor(Color.black);
g.fillOval (150, 70, 50, 50); // red light
g.fillOval (150, 150, 50, 50); // yellow light
g.fillOval (150, 230, 50, 50); // green light
switch (colourNum)
{
case 1: g.setColor (Color.red);
g.fillOval (150,70,50,50); // red light
msg="STOP";
g.drawString(msg,210,100);
break;
case 2: g.setColor(Color.yellow);
g.fillOval (150,150,50,50); // yellow light
msg="READY";
g.drawString(msg,210,180);
break;
case 3: g.setColor(Color.green);
g.fillOval (150,230,50,50); // green light
msg="GO";
g.drawString(msg,210,260);
break;
}
}
}
56
JAVA PROGRAMMING LAB MLRITM
57
JAVA PROGRAMMING LAB MLRITM
58
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
1. What is AWT?
2. What is component?
3. How to interact with the Java system at runtime?
4. What is the super class of all components of Java?
5. What is a container?
6. What is the super class of all containers?
7. What is a layout manager?
8. How many layout managers are available in Java?
9. What is the style of arranging components in a container by FlowLayout
manager?
10. How BorderLayout places the components?
11. What is the style of GridLayout?
12. When CardLayout can be used?
13. When GridBagLayout can be used?
14. What is a panel?
15. What are the default layout managers for containers?
16. Which layout manager gives the minimum size to a component?
17. What is the method used to place some text in the text field?
18. What is the method used to get the data entered by the user in the text field?
19. What for text field is used?
20. What is the difference between text field and text area?
21. What is the method used to change the characters entered by the user in the text
field (used for password)?
22. How to make the text field non-editable by the user (user cannot enter anything)?
23. What is the method used to change the background color of components like text
field?
24. What is the method used to change the foreground (text) color of components like
text field?
25. What is the method used to know the label of the button clicked by the user?
26. What is the super class of TextField and TextArea?
27. What is the method used to change the text of a Label?
28. What is the method used to retrieve the text of a Label?
29. How many ways you can align the label in a container?
30. What is the method used to change the label of a button?
31. What is the method used to retrieve the label of a button?
32. What is HeadlessException?
33. What is the listener used to handle the events of a text field?
34. What are the component and container class?
35. What is the parameter specification for the public static void main method?
36. What is the difference between the paint() and repaint() method?
37. What interface is extended by AWT event listener?
59
JAVA PROGRAMMING LAB MLRITM
60
JAVA PROGRAMMING LAB MLRITM
Week-8
Aim: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:
abstract class Shape
{
int height;
int width;
int radius;
abstract int printArea();
}
61
JAVA PROGRAMMING LAB MLRITM
{
radius=r;
}
int printArea()
{
System.out.println("Inside Area for Circle.");
int area=(int)(3.14*radius*radius);
return(area);
}
}
public class AbstractDemo
{
public static void main(String args[])
{
Rectangle r = new Rectangle(10, 5);
Triangle t = new Triangle(10, 8);
Circle c=new Circle(10);
}
}
Output:
62
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
1. What is abstraction in java?
2. How to achieve abstraction in java?
3. What is abstract class in java?
4. Can we create instance of abstract class?
5. Can we define abstract class without abstract method?
6. Can we declare abstract method in non-abstract class?
7. What is interface in java?
8. Why we use interface in java?
9. Can we create instance of interface?
10. Can we declare abstract method as static?
11. Can we declare abstract method as final?
12. Can we declare abstract method as private?
13. Can we use public, protected and default modifiers with abstract method?
14. Can we declare local inner class as abstract?
15. Method in interface are by default public and abstract. true or false?
16. Data member in interface are by default public, static, and final. true of false?
17. Can abstract class implements interface in java?
18. Can we use abstract keyword with constructor?
19. Abstract classes can be nested. true or false?
20. Can abstract class have constructor in java?
21. Difference between abstraction and encapsulation in java?
22. What is the difference between abstract class and interface?
23. Can abstract method declaration include throws clause?
24. What will happen if we do not override all the abstract methods in sub-class?
25. How can we define an abstract class?
26. How to declare an abstract method?
27. Can we define abstract class without abstract method?
28. Can we create object object for abstract class?
29. Is is possible to declare abstract method as static?
30. Can we declare abstract method as final?
31. Is it possible to declare abstract method as public ?
32. Is it possible to declare abstract method with default?
33. Is it possible to declare abstract method with protected modifier?
34. What are the valid and invalid keywords or modifier with abstract class?
35. Can abstract method declaration include throws clause?
36. What happens if sub class not overriding abstract methods?
37. Can we escape of overriding abstract class in sub class which is extending abstract class?
38. What does it mean that a method or class is abstract?
39. What must a class do to implement an interface?
40. What is interface? How to support multiple inhertance in Java?
41. Can you make an instance of an abstract class?
42. If interface & abstract class have same methods and those methods contain no implementation,
which one would you prefer?
43. Why the main method is static in java?
44. What happens if you remove static modifier from the main method?
63
JAVA PROGRAMMING LAB MLRITM
64
JAVA PROGRAMMING LAB MLRITM
Week-9
Aim: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 java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class A extends Frame
{
public A()
{
setSize(600, 600);
GridLayout g = new GridLayout(0, 4);
setLayout(g);
try
{
FileInputStream fin = new FileInputStream("");
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 Label(i));
}
}
}
catch (Exception ex)
{
}
pack();
setVisible(true);
65
JAVA PROGRAMMING LAB MLRITM
}
}
public class TableData
{
public static void main(String[] args)
{
A a = new A();
}
}
Output:
66
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
67
JAVA PROGRAMMING LAB MLRITM
43. What is the use of GridLayout(int rows, int cols, int hgap, int vgap)
44. What is method used to find number of rows in GridLayout?
45. What is method used to find number of columns in GridLayout?
46. What is method used to find vertical gap between the components in GridLayout?
47. How to set number of columns in GridLayout?
48. How to set number of rows in GridLayout?
49. How to set vertical gap between the components in GridLayout?
50. How to set horizontal gap between the components in GridLayout?
68
JAVA PROGRAMMING LAB MLRITM
Week-10
Aim: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:
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet {
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter {
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me) {
adapterDemo.showStatus("Mouse clicked");
}
}
class MyMouseMotionAdapter extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo) {
this.adapterDemo = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
adapterDemo.showStatus("Mouse dragged");
}
}
69
JAVA PROGRAMMING LAB MLRITM
Output:
70
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
1. What is the purpose of Event object?
2. What is an action event?
3. What are the different kinds of event listeners?
4. What is event adapter class?
5. When should we use an event adapter class?
6. What is the relationship between an event-listener interface and an event-adapter class?
7. What is the difference between the paint() and repaint() methods?
8. What is the Event handling?
9. What is Adapter class?
10. What interface is extended by AWT event listener?
11. What is an event and what are the models available for event handling?
12. What are the advantages of the event delegation model over the event inheritance model?
13. What event results from the clicking of a button?
14. What is source?
15. What is a listener?
16. What is the highest level event class of the event delegation model?
17. How key events can be handled?
18. How mouse events can be handled?
19. What is an event?
20. How to add listener?
21. How to remove listener?
22. What is the super class of all the event classes?
23. Which package contains all the events?
24. What are the methods of EventObject class?
25. What is the super class of all the awt event classes?
26. What is the use of ActionEvent?
27. Which event is generated when button is clicked?
28. Which event is generated when scroll bar is manipulated?
29. Which event is generated when a component hidden?
30. Which event is generated when component is added or hidden?
31. Which event is generated when component gains or losses keyboard focus?
32. What is the abstract super class of all input events?
33. Which event is generated when input is received from keyboard?
34. Which event is generated when the mouse wheel is moved?
35. Which event is generated when the text are is changed?
36. What are the methods of MouseListener interface?
37. What are the methods of MouseMotionListener interface?
38. What are the methods of MouseWheelListener interface?
39. What is the adapter class used to handle mouse events?
71
JAVA PROGRAMMING LAB MLRITM
72
JAVA PROGRAMMING LAB MLRITM
Week-11
Aim: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.util.*;
import java.io.*;
public class PhoneDictionary
{
public static void main(String[] args)
{
try
{
FileInputStream fs = new FileInputStream("E:\\siva\\phone.txt");
Scanner sc = new Scanner(fs).useDelimiter("\\s+");
Hashtable<String, String> ht = new Hashtable<String, String>();
String[] arrayList;
String a;
System.out.println("Student Phone numbers are");
while (sc.hasNext())
{
a = sc.nextLine();
arrayList = a.split("\\s+");
ht.put(arrayList[0], arrayList[1]);
System.out.println(arrayList[0] + ":" + arrayList[1]);
}
System.out.println("MENU");
System.out.println("1.Search by Name");
System.out.println("2.Search by Mobile");
System.out.println("3.Exit");
String opt = "";
String name, mobile;
Scanner s = new Scanner(System.in);
while (opt != "3")
{
System.out.println("Enter Your Option (1,2,3): ");
opt = s.next();
73
JAVA PROGRAMMING LAB MLRITM
switch (opt)
{
case "1": System.out.println("Enter Name");
name = s.next();
if (ht.containsKey(name))
{
System.out.println("Mobile is " + ht.get(name));
}
else
{
System.out.println("Not Found");
}
break;
case "2": System.out.println("Enter mobile");
mobile = s.next();
if (ht.containsValue(mobile))
{
for (Map.Entry e : ht.entrySet())
{
if (mobile.equals(e.getValue()))
{
System.out.println("Name is " + e.getKey());
}
}
}
else
{
System.out.println("Not Found");
}
break;
case "3": opt = "3";
System.out.println("Menu Successfully Exited");
break;
default: System.out.println("Choose Option betwen 1 and Three");
break;
}
}
}
catch (Exception ex)
{
74
JAVA PROGRAMMING LAB MLRITM
System.out.println(ex.getMessage());
}
}
}
Output:
75
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
76
JAVA PROGRAMMING LAB MLRITM
77
JAVA PROGRAMMING LAB MLRITM
Week-12
Aim:Write a Java program that correctly implements the producer – consumer problem using
the concept of interthread communication.
Program:
class Q
{
int n;
boolean valueSet = 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;
}
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
78
JAVA PROGRAMMING LAB MLRITM
{
Q q;
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
{
Q q;
Consumer(Q q)
{
this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{
while(true)
{
q.get();
}
}
}
class PCFixed
{
public static void main(String args[])
{
Q q = new Q();
new Producer(q);
new Consumer(q);
}
79
JAVA PROGRAMMING LAB MLRITM
Output:
80
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
81
JAVA PROGRAMMING LAB MLRITM
82
JAVA PROGRAMMING LAB MLRITM
Week-13
Aim:Write a Java program to list all the files in a directory including the files present in
all its subdirectories.
Program:
import java.io.File;
public class ListFiles
{
public void listFilesAndFilesSubDirectories(String directoryName)
{
File directory = new File(directoryName);
File[] fList = directory.listFiles();
for (File file : fList)
{
if (file.isFile())
{
System.out.println(file.getAbsolutePath());
}
else if (file.isDirectory())
{
listFilesAndFilesSubDirectories(file.getAbsolutePath());
}
}
}
public static void main (String[] args)
{
ListFiles l= new ListFiles();
final String directoryWindows ="D:\\siva";
System.out.println("The following are the list of all the files in a directory including
the files present in all its subdirectories.");
l.listFilesAndFilesSubDirectories(directoryWindows);
}
}
83
JAVA PROGRAMMING LAB MLRITM
Output:
84
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
85
JAVA PROGRAMMING LAB MLRITM
86
JAVA PROGRAMMING LAB MLRITM
Week-14
Aim:Write a Java program that implements Quick sort algorithm for sorting a list of names in
ascending order
Program:
import java.util.Scanner;
public class StringSort
{
String names[];
int length;
void sort(String array[])
{
if (array == null || array.length == 0)
{
return;
}
this.names = array;
this.length = array.length;
quickSort(0, length - 1);
}
void quickSort(int lowerIndex, int higherIndex)
{
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++;
87
JAVA PROGRAMMING LAB MLRITM
j--;
}
}
//call quickSort recursively
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;
}
public static void main(String[] args)
{
StringSort sorter= new StringSort();
int n;
System.out.println("enter number of strings to be sorted:");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
String words[] =new String[n];
System.out.println("\nEnter the strings to be sorted:");
for(int i=0;i<n;i++)
words[i]=sc.next();
System.out.println("\nStrings after sorting:\n");
sorter.sort(words);
for (String i : words)
{
System.out.println(i);
}
System.out.println("");
}
}
88
JAVA PROGRAMMING LAB MLRITM
Output:
89
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
90
JAVA PROGRAMMING LAB MLRITM
91
JAVA PROGRAMMING LAB MLRITM
Week-15
Aim: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:
import java.util.Arrays;
import java.util.Scanner;
int temp;
Arr[j - 1] = Arr[j];
Arr[j] = temp;
count++;
return Arr;
92
JAVA PROGRAMMING LAB MLRITM
int n=sc.nextInt();
int i;
for(i=0;i<n;i++)
Arr[i]=sc.nextInt();
System.out.println("");
Output:
93
JAVA PROGRAMMING LAB MLRITM
Viva Questions:
1. What do you mean by an Array?
2. How to create an Array?
3. What are the advantages and disadvantages of Array?
4. Can we change the size of an array at run time?
5. Can you declare an array without assigning the size of an array?
6. What is the default value of Array?
7. How to print element of Array?
8. How to compare Two Arrays?
9. How to sort an Array?
10. Can we declare array size as a negative number?
11. When will we get ArrayStoreException?
12. Can we add or delete an element after assigning an array?
13. What is the meaning of anonymous array? Explain with an example?
14. Is there any difference between int[] a and int a[]?
15. There are 2 int type array data type. One is containing 50 elements, and another one is
containing 30 elements. Can we assign the array of 50 elements to an array of 30
elements?
16. int a[] = new int[3]{1, 2, 3} – is it a right way to declare arrays in java?
17. How to copy an array into another array?
18. What are “jagged” arrays in java?
19. When ArrayIndexOutOfBoundsException occurs?
20. Can you explain different steps of declaring multidimensional arrays in Java?
21. How do we search a specific element in an array?
22. If you do not initialize an array what will happen?
23. How do we find duplicate elements in an array?
24. Can we use Generics with the array?
25. How to iterate an array in java?
26. Where is the memory allocated for arrays in Java?
27. Can you tell me the class name of an array in Java?
28. “int a[] = new int[3]{1, 2, 3}” – This a legal way of defining the arrays?
29. What is the two-dimensional array?
30. Do we have 3-dimensional arrays in Java?
31. Can we make array volatile in Java?
32. Can you tell me the differences between Array and ArrayList?
33. We know that Arrays are objects so why cannot we write strArray.length()?
34. How to check array contains value or not?
35. How to get largest and smallest number in an array?
36. How to do the intersection of two sorted arrays?
37. How to get top two numbers from an array?
38. How to find the length an array?
39. What is the difference between length() and length?
94
JAVA PROGRAMMING LAB MLRITM
95