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

java&OOP THROUGH JAVA JAVA

Java

Uploaded by

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

java&OOP THROUGH JAVA JAVA

Java

Uploaded by

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

RISHI MS INSTITUTE OF ENGINEERING &

TECHNOLOGY FOR WOMEN


(Approved by AICTE, New Delhi and Affiliated to JNTUH)
Nizampet Cross Road, JNTUH Kukatpally Hyderabad–500085

LABORATORY MANUAL
(OBJECT ORIENTED PROGRAMMING THROUGH
JAVA/ JAVA PROGRAMMING LAB)
(R22 Regulations)

For

B. Tech
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
&
INFORMATION TECHNOOGY
INDEX

S.NO TOPIC PAGENO

I List of Experiments ii

II V/M/POs/PSOs/PEOs iv

III Syllabus x

IV Course Objectives &Course Outcomes xIi

i
List of Experiments

Exp. Experiment Name Page No.


No.
Use Eclipse or Net bean platform and acquaint yourself
with the various menus. Create a test project, add a test
1 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.
Write a Java program that works as a simple calculator. Use
2 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.

A) Develop an applet in Java that displays a simple


3 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.
Write a Java program that creates a user interface to
4 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.
Write a Java program that implements a multi-thread
5 application that has three threads. First thread generates a
random integer every 1 second and if the value is even, the
second thread computes the square of the number and
prints. If the value is odd, the third thread will print the
value of the cube of the number.
Write a Java program for the following:
6 Create a doubly linked list of elements.
Delete a given element from the above list.
Display the contents of the list after deletion.
Write a Java program that simulates a traffic light. The
7 program lets the user select one of three lights: red, yellow,

ii
or green with radio buttons. On selecting a button, an
appropriate message with “Stop” or “Ready” or “Go”
should appear above the buttons in the selected color.
Initially, there is no message shown.
Write a Java program to create an abstract class named
8 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.
Suppose that a table named Table.txt is stored in a text file.
9 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.
Write a Java program that handles all mouse events and
10 shows the event name at the center of the window when a
mouse event is fired (Use Adapter classes).
Write a Java program that loads names and phone numbers
11 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).
Write a Java program that correctly implements the
12 producer – consumer problem using the concept of inter
thread communication.
Write a Java program to list all the files in a directory
13 including the files present in all its subdirectories.

iii
RISHI M.S. INSTITUTE OF ENGINEERING & TECHNOLOGY FOR
WOMEN
(Affiliated to JNTUH University, Approved by AICTE)
Department of
Information Technology& Computer Science And Engineering

Vision of the institution:

To be a center of excellence in producing women engineers and scientists who are


professionally competent social leaders to face multi-disciplinary global environment by
imparting quality technical education, values and ethics through innovation methods of
teaching and learning.

Mission of the institution:

• To promote women technocrats capable enough to resolve the problems faced by


the society using the knowledge imparted.
• To prepare self-reliant women engineering for technological growth of the nation
and society by laying strong theoretical foundation accompanied by wide practical
training.
• To equip the young women with creative thinking capabilities and empowering
them towards innovation.

iv
RISHI M.S. INSTITUTE OF ENGINEERING & TECHNOLOGY FOR
WOMEN
(Affiliated to JNTUH University, Approved by AICTE)
Department of
Information Technology& Computer Science And Engineering

Vision & Mission of Department

Vision of the department

To empower women by providing cutting-edge technology to female technocrats in the


fields of Information Technology, allowing them to develop into competent engineers and
entrepreneurs.

Mission of the department

• Adopting creative techniques to nurture and strengthen the core skill of Computer
Science.
• Introduce students to the most recent technological advancements.
• Impart quality education; improve the research, entrepreneurial, and employability
skills of women technocrats.
• Instill professional ethics and a sense of social responsibility in students.
• Strengthen the Industry-Academia interface, which will enable graduates to
emerge as academic leaders or inspiring entrepreneurs

v
RISHI M.S. INSTITUTE OF ENGINEERING & TECHNOLOGY FOR
WOMEN
(Affiliated to JNTUH University, Approved by AICTE)
Department of
Information Technology& Computer Science And Engineering

Program out comes (POs)

1. Engineering Knowledge: Apply the knowledge of mathematics, science,


engineering fundamentals, and an engineering specialization to the solution
of complex engineering problems.
2. Problem Analysis: Identify, formulate, review research literature, and
analyze complex engineering problems reaching substantiated conclusions
using first principles of mathematics, natural sciences, and engineering
sciences.
3. Design/Development of Solutions: Design solutions for complex
engineering problems and design system components or processes that meet
the specified needs with appropriate consideration for the public health and
safety, and the cultural, societal, and environmental considerations.
4. Conduct Investigations of Complex Problems: Use research-based
knowledge and research methods including design of experiments, analysis
and interpretation of data, and synthesis of the information to provide valid
conclusions.
5. Modern Tool Usage: Create, select and apply appropriate techniques,
resources and modern engineering and IT tools including prediction and
modeling to complex engineering activities with an understanding of the
limitations.
6. The Engineer and Society: Apply reasoning informed by the contextual
knowledge to assess societal, health, safety, legal and cultural issues and
the consequent responsibilities relevant to the professional engineering
practice.
7. Environment and Sustainability: Understand the impact of the
professional engineering solutions in societal and environmental contexts,
and demonstrate the knowledge of and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of the engineering practice.
9. Individual and Team Work: Function effectively as an individual, and as
a member or leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering
activities with the engineering community and with society at large, such
as, being able to comprehend and write effective reports and design

vi
documentation, make effective presentations, and give and receive clear
instructions.
11. Project Management and Finance: Demonstrate knowledge and
understanding of the engineering and management principles and apply
these to one’s own work, as a member and leader in a team, to manage
projects and in multidisciplinary environments.
12. Life-long Learning: Recognize the need for, and have the preparation and
ability to engage in independent and life-long learning in the broadest
context of technological

vii
RISHI M.S. INSTITUTE OF ENGINEERING & TECHNOLOGY FOR
WOMEN
(Affiliated to JNTUH University, Approved by AICTE)
Department of
Information Technology& Computer Science And Engineering

Program specific outcomes (PSOs)

PSO 1: Improve the student's ability to decipher the basic principles and methodology
of computer systems. Improve the student’s ability to absorb facts and
technical ideas in order to build and develop software.
PSO2: The capacity to create novel job routes as an entrepreneur using modern
computer languages and evolving technologies like SDLC, Python,
Machine Learning, Social Networks, Cyber Security, Mobile Apps etc.

viii
RISHI M.S. INSTITUTE OF ENGINEERING & TECHNOLOGY FOR
WOMEN
(Affiliated to JNTUH University, Approved by AICTE)
Department of
Information Technology& Computer Science And Engineering

Program educational objectives (PEOs)

PEO-1: Engineering graduates with excellent fundamental and technical


skills will have successful careers in industry, meeting the needs of
Indian and worldwide firms.

PEO-2: With determination, development, self-reliance, leadership, morality, and


moral principles, engineering graduates will become successful entrepreneurs
who will ever age employability.

PEO-3: To support personal and organizational progress, engineering graduates will


pursue higher education and engage in lifelong learning.

ix
SYLLABUS
OBJECT ORIENTED PROGRAMMING THROUGH JAVA

/JAVA PROGRAMMING LAB

B. TECH II Year II Sem

Week-1:

1. Use Eclipse or Net bean platform and acquaint yourself with the various menus. Create a
test project, adda 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.

Week-2:

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.

Week-3:

5. Write a Java program that implements a multi-thread application that has three threads. First
thread generates a random integer every 1 second and if the value is even, the second thread
computes the square of the number and prints. If the value is odd, the third thread will print the
value of the cube of the number.

6. Write a Java program for the following:

x
Create a doubly linked list of elements.

Delete a given element from the above list.

Display the contents of the list after deletion.

Week-4:

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

Week-5:

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

Week-6:

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 inter thread communication.

Week-7:

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

xi
Course Objectives:
1. To provide an understanding of the design aspects of operating system
concepts through simulation.
2. Introduce basic Unix commands, system call interface for process
management, inter-process communication and I/O in Unix.

Course Outcomes: After learning the contents of this course the student is able to
CO1. Simulate and implement operating system concepts such as
scheduling, deadlock

management, file management and memory management.

CO2. Able to implement C programs using Unix system calls

CO-PO MAPPING:

CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12

(OBJECT CO1 2 3 3 2 2 2 2
ORIENTED
PROGRAM CO2 2 3 1 1 3 2 3
MING
THROUGH CO3 2 2 3 3 3 3 1
JAVA/ JAVA
PROGRAM
MING LAB)

CO-PSO MAPPING:
PSO-1 PSO-2
CO1 3 2
CO2 3 2
CO3 3 3

xii
WEEK-1
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 programs;

public class Experiment {

public static void main(String[] args) {


System.out.println("\n Program for finding even no: ");
for(int i=2;i<=20;i++)
{
if(i%2==0)
{
System.out.print("\n "+i);
}

xiii
OUTPUT :

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

package programs;

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class CalculatorPanel extends Applet
implements ActionListener
{
String msg=" ";
Int p,q,result;
TextField t1;
Button b[]=new Button[10];
Button add,sub,mul,div,clear,mod,EQ;
char OP;
public void init()
{
t1=new TextField(10);
GridLayout gl=new GridLayout(4,5);
setLayout(gl);
for(int i=0;i<10;i++)
{
b[i]=new Button(""+i);
}
add=new Button("add");
sub=new Button("sub");
mul=new Button("mul");
div=new Button("div");
mod=new Button("mod");
clear=new Button("clear");
EQ=new Button("EQ");
t1.addActionListener(this);
add(t1);
for(int i=0;i<10;i++)
{
add(b[i]);
}
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);

xv
}
add.addActionListener(this);
sub.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
mod.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
string str=ae.getActionCommand();
char ch=str.charAt(0);
if ( Character.isDigit(ch))
t1.setText(t1.getText()+str);
else if(str.equals("add")) {
p=Integer.parseInt(t1.getText());
OP='+';
t1.setText("");
}
else if(str.equals("sub")) {
p=Integer.parseInt(t1.getText());
OP='-';
t1.setText("");
}
else if(str.equals("mul")) {
p=Integer.parseInt(t1.getText());
OP='*';
t1.setText("");
}
else if(str.equals("div")) {
p=Integer.parseInt(t1.getText());
OP='/';
t1.setText("");
}
else if(str.equals("mod")) {
p=Integer.parseInt(t1.getText());
OP='%';
t1.setText("");
}
if(str.equals("EQ")) {
q=Integer.parseInt(t1.getText());
if(OP=='+')
result=p+q;
else if(OP=='-')
result=p-q;
else if(OP=='*')
result=p*q;
else if(OP=='/')
result=p/q;
else if(OP=='%')
result=p%q;
t1.setText(""+result);
}
if(str.equals("clear")) {
t1.setText("");

xvi
}
}
}

OUTPUT :
javac CalculatorPanel.java

xvii
WEEK-2
• 3. a) Develop an applet that displays a simple message.
Program:
package programs;

import java.applet.Applet;
import java.awt.Graphics;

public class Applets extends Applet


{
Public void main paint(Graphics g)
{
g.drawString("All THE BEST for your Future",10,80);
}

OUTPUT :

Explanation :

• The java program begins with two import statements.


• The first import statement imports the Applet class from applet package. Every AWT-
based(Abstract Window Toolkit) applet that you create must be a subclass (either directly
or indirectly) of Applet class.

xviii
• The second statement import the Graphics class from awt package.
• The next line in the program declares the class Applets. This class must be declared as
public, because it will be accessed by code that is outside the program. Inside
Applets, paint( ) is declared. This method is defined by the AWT and must be overridden
by the applet.
• Inside paint( ) is a call to drawString( ), which is a member of the Graphics class. This
method outputs a string beginning at the specified X,Y location. It has the following
general form:
Void drawstring(String message, int x, int y);
Note:
• The applet does not have a main( ) method.
• Unlike Java programs, applets do not begin execution at main( ). In fact, most applets
don’t even have a main( ) method.
• Instead, an applet begins execution when the name of its class is passed to an applet
viewer or to a network browser.

xix
3 b) Develop an Applet that receives an integer in one text field & compute its factorial
value & returns it in another text filed when the button “Compute” is clicked.
Program :
package programs;

import java.awt.*;
import java.lang.String;
import java.awt.event.*;
import java.applet.Applet;
public class Factorial 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();
}
}

xx
OUTPUT :

xxi
4. Write a program that creates a user interface to perform integer divisions. The user
enters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2
is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were
not an integer, the program would throw a NumberFormatException. If Num2 were Zero,
the program would throw an Arithmetic Exception Display the exception in a message
dialog box.
Program :
package programs;

import java.awt.*;
import javax.swing.*;
import java.applet.Applet;
import java.awt.event.*;
publicclassDivisionextends Applet implements ActionListener{
TextField t1,t2,t3;
Button b;
Label L1,L2,L3,L4;
String s;
Division e;
publicvoid init()
{
e=this;
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
L1=new Label("enter num1");
L2=new Label("enter num2");
L3=new Label("Result is");
L4=new Label("Division of 2 numbers");
b=new Button("Divide");
add(L4);
add(L1);
add(t1);
add(L2);
add(t2);
add(L3);
add(t3);
add(b);
b.addActionListener(this);
}
publicvoid actionPerformed(ActionEvent ae)
{
try
{
intnum1=Integer.parseInt(t1.getText());
intnum2=Integer.parseInt(t2.getText());
s=""+(num1/num2);
t3.setText(s);
}
catch(ArithmeticException a)

xxii
{
JOptionPane.showMessageDialog(null,"Divide by zero");
}

catch(NumberFormatException b)
{
JOptionPane.showMessageDialog(null,"NumberFormateException");
}
}
}

OUTPUT :

xxiii
WEEK-3
5.) Write a java program that implements a multi-thread application that has three
threads. First thread generates random integer every 1 second and if the value is even,
second thread computes the square of the number and prints. If the value is odd, the third
thread will print the value of cube of the number.
Program :
package programs;

import java.util.Random;
public class Multithread {
public static void main(String args[])
{
A a=new A("one");
a.start();
}
}
class A extends Thread
{
String tname;
Random r;
Thread t1,t2;
A(String x)
{
this.tname=x;
}
public void run()
{
try
{
int num=0;
r=new Random();
num=r.nextInt(100);
for(int i=0;i<10;i++)
{
if(num%2==0)
{
t1=new Thread(new even(num));
t1.start();
}
else

{
t2=new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
} }
catch(InterruptedException e)
{
System.out.println("Exception is"+e);

xxiv
}
catch(Exception a)
{
System.out.println("Exception is"+a);
} } }
class even implements Runnable
{
int x;
even(int x) {
this.x=x;
}
public void run() {
System.out.println("num is even"+x+"its square is"+(x*x));
}}
class odd implements Runnable
{
int x;
odd(int x) {this.x=x; }public void run() {
System.out.println("num is odd"+x+"its cube is"+(x*x*x)); }
}

OUTPUT :

xxv
Experiment-6 :
Write a Java program for the following:
i) Create a doubly linked list of elements.
ii) Delete a given element from the above list.
iii) Display the contents of the list after deletion.
Program :
package programs;
import java.util.Scanner;
class Node
{
protectedintdata;
protected Node next, prev;
public Node()
{
next = null;
prev = null;
data = 0;
}

public Node(intd, Node n, Node p)


{
data = d;
next = n;
prev = p;
}

publicvoid setLinkNext(Node n)
{
next = n;
}
publicvoid setLinkPrev(Node p)
{
prev = p;
}
public Node getLinkNext()
{
returnnext;
}
public Node getLinkPrev()
{
returnprev;
}

publicvoid setData(intd)
{
data = d;
}
publicint getData()
{
returndata;
}
}

xxvi
class linkedList
{
protected Node start;
protected Node end ;
publicintsize;
public linkedList()
{
start = null;
end = null;
size = 0;
}
publicboolean isEmpty()
{
returnstart == null;
}
publicint getSize()
{
returnsize;
}
publicvoid insertAtStart(intval)
{
Node nptr = new Node(val, null, null);
if(start == null)
{
start = nptr;
end = start;
}
else
{
start.setLinkPrev(nptr);
nptr.setLinkNext(start);
start = nptr;
}
size++;
}
publicvoid insertAtEnd(intval)
{
Node nptr = new Node(val, null, null);
if(start == null)
{
start = nptr;
end = start;
}
else
{
nptr.setLinkPrev(end);
end.setLinkNext(nptr);
end = nptr;
}
size++;
}
publicvoid insertAtPos(intval , intpos)
{
Node nptr = new Node(val, null, null);
if (pos == 1)
{
insertAtStart(val);

xxvii
return;
}
Node ptr = start;
for (inti = 2; i<= size; i++)
{
if (beginning == pos)
{
Node tmp = ptr.getLinkNext();
ptr.setLinkNext(nptr);
nptr.setLinkPrev(ptr);
nptr.setLinkNext(tmp);
tmp.setLinkPrev(nptr);
}
ptr = ptr.getLinkNext();
}
size++ ;
}
publicvoid deleteAtPos(intpos)
{
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 (inti = 2; i<= size; i++)
{
if (beginning == pos)
{
Node p = ptr.getLinkPrev();
Node n = ptr.getLinkNext();

p.setLinkNext(n);
n.setLinkPrev(p);
size-- ;
return;
}
ptr = ptr.getLinkNext();
}
}
publicvoid display()
{

xxviii
System.out.print(“\nDoubly Linked List = “);
if (size == 0)
{
System.out.print(“empty\n”);
return;
}
if (start.getLinkNext() == null)
{
System.out.println(start.getData() );
return;
}
Node ptr = start;
System.out.print(start.getData()+ “ <-> “);
ptr = start.getLinkNext();
while (ptr.getLinkNext() != null)
{
System.out.print(ptr.getData()+ “ <-> “);
ptr = ptr.getLinkNext();
}
System.out.print(ptr.getData()+ “\n”);
}
}
publicclass DoublyLinkedList
{
publicstaticvoid main(String[] args)
{
Scanner scan = new Scanner(System.in);
// Creating object of linkedList
linkedList list = new linkedList();
System.out.println(“Doubly Linked List Insertion and Deletion”);
charch;

do
{
System.out.println(“Doubly Linked List Operations”);
System.out.println(“1. Insert at the beginning”);
System.out.println(“2. Insert at the 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”);

intchoice = scan.nextInt();
switch (choice)
{
case 1 :
System.out.println(“Enter integer element to insert”);
list.insertAtStart( scan.nextInt() );
break;
case 2 :
System.out.println(“Enter integer element to insert”);
list.insertAtEnd( scan.nextInt() );
break;
case 3 :
System.out.println(“Enter integer element to insert”);
intnum = scan.nextInt() ;
System.out.println(“Enter position”);

xxix
intpos = scan.nextInt() ;
if (pos< 1 || pos>list.getSize() )
System.out.println(“Invalid position\n”);
else
list.insertAtPos(num, pos);
break;
case 4 :
System.out.println(“Enter position”);
intp = scan.nextInt() ;
if (p< 1 || p>list.getSize() )
System.out.println(“Invalid position\n”);
else
list.deleteAtPos(p);
break;
case 5 :
System.out.println(“Empty status = “+ list.isEmpty());
break;
case 6 :
System.out.println(“Size = “+ list.getSize() +” \n”);
break;
default :
System.out.println(“Wrong Entry \n “);
break;
}
list.display();
System.out.println(“\nDo you want to continue (Type y or n)
\n”);
ch = scan.next().charAt(0);

} while (ch == ‘Y’|| ch == ‘y’);


}
}

New

package programs;
import java.util.Scanner;
class Node
{
protected int data;
protected Node next, prev;
public Node()
{
next = null;
prev = null;
data = 0;
}

public Node(int d, Node n, Node p)


{
data = d;
next = n;
prev = p;
}

xxx
public void setLinkNext(Node n)
{
next = n;
}
public void setLinkPrev(Node p)
{
prev = p;
}
public Node getLinkNext()
{
return next;
}
public Node getLinkPrev()
{
return prev;
}

public void setData(int d)


{
data = d;
}
public int getData()
{
return data;
}
}
class linkedList
{
protected Node start;
protected Node end ;
public int size;
public linkedList()
{
start = null;
end = null;
size = 0;
}
public 31oolean isEmpty()
{
return start == null;
}
public int getSize()
{
return size;
}
public void insertAtStart(int val)
{
Node nptr = new Node(val, null, null);
if(start == null)
{
start = nptr;
end = start;
}
else
{
start.setLinkPrev(nptr);
nptr.setLinkNext(start);

xxxi
start = nptr;
}
size++;
}
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++;
}
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 beginning = 2; i<= size; i++)
{
if (beginning == pos)
{
Node tmp = ptr.getLinkNext();
ptr.setLinkNext(nptr);
nptr.setLinkPrev(ptr);
nptr.setLinkNext(tmp);
tmp.setLinkPrev(nptr);
}
ptr = ptr.getLinkNext();
}
size++ ;
}
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--;

xxxii
return ;
}
if (pos == size)
{
end = end.getLinkPrev();
end.setLinkNext(null);
size-- ;
}
Node ptr = start.getLinkNext();
for (int beginning = 2; i<= size; i++)
{
if (beginning == pos)
{
Node p = ptr.getLinkPrev();
Node n = ptr.getLinkNext();

p.setLinkNext(n);
n.setLinkPrev(p);
size-- ;
return;
}
ptr = ptr.getLinkNext();
}
}
public void display()
{
System.out.print(“\nDoubly Linked List = “);
if (size == 0)
{
System.out.print(“empty\n”);
return;
}
if (start.getLinkNext() == null)
{
System.out.println(start.getData() );
return;
}
Node ptr = start;
System.out.print(start.getData()+ “ <-> “);
ptr = start.getLinkNext();
while (ptr.getLinkNext() != null)
{
System.out.print(ptr.getData()+ “ <-> “);
ptr = ptr.getLinkNext();
}
System.out.print(ptr.getData()+ “\n”);
}
}
public class DoublyLinkedList
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
// Creating object of linkedList
linkedList list = new linkedList();
System.out.println(“Doubly Linked List Insertion and Deletion”);
char ch;

xxxiii
do
{
System.out.println(“Doubly Linked List Operations”);
System.out.println(“1. Insert at the beginning”);
System.out.println(“2. Insert at the 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”);

int choice = scan.nextInt();


switch (choice)
{
case 1 :
System.out.println(“Enter integer element to insert”);
list.insertAtStart( scan.nextInt() );
break;
case 2 :
System.out.println(“Enter integer element to insert”);
list.insertAtEnd( scan.nextInt() );
break;
case 3 :
System.out.println(“Enter integer element to insert”);
int num = scan.nextInt() ;
System.out.println(“Enter position”);
int pos = scan.nextInt() ;
if (pos< 1 || pos>list.getSize() )
System.out.println(“Invalid position\n”);
else
list.insertAtPos(num, pos);
break;
case 4 :
System.out.println(“Enter position”);
int p = scan.nextInt() ;
if (p< 1 || p>list.getSize() )
System.out.println(“Invalid position\n”);
else
list.deleteAtPos(p);
break;
case 5 :
System.out.println(“Empty status = “+ list.isEmpty());
break;
case 6 :
System.out.println(“Size = “+ list.getSize() +” \n”);
break;
default :
System.out.println(“Wrong Entry \n “);
break;
}
list.display();
System.out.println(“\nDo you want to continue (Type y or n)
\n”);
ch = scan.next().charAt(0);

} while (ch == ‘Y’|| ch == ‘y’);


}

xxxiv
}

OUTPUT :
Doubly Linked List Insertion and Deletion
Doubly Linked List Operations
1. insert at the beginning
2. insert at the end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
55

Doubly Linked List = 55

Do you want to continue (Type y or n)

y
Doubly Linked List Operations
1. insert at the beginning
2. insert at the end
3. insert at position
4. delete at position
5. check empty
6. get size
1
Enter integer element to insert
78

Doubly Linked List = 78 <-> 55

Do you want to continue (Type y or n)

y
Doubly Linked List Operations
1. insert at the beginning
2. insert at the end
3. insert at position
4. delete at position
5. check empty
6. get size
2
Enter integer element to insert
89

Doubly Linked List = 78 <-> 55 <-> 89

Do you want to continue (Type y or n)

y
Doubly Linked List Operations
1. insert at the beginning
2. insert at the end

xxxv
3. insert at position
4. delete at position
5. check empty
6. get size
3
Enter integer element to insert
56
Enter position
2

Doubly Linked List = 78 <-> 56 <-> 55 <-> 89

Do you want to continue (Type y or n)

y
Doubly Linked List Operations
1. insert at the beginning
2. insert at the end
3. insert at position
4. delete at position
5. check empty
6. get size
4
Enter position
3

Doubly Linked List = 78 <-> 56 <-> 89

Do you want to continue (Type y or n)

y
Doubly Linked List Operations
1. insert at the beginning
2. insert at the end
3. insert at position
4. delete at position
5. check empty
6. get size
5
Empty status = false

Doubly Linked List = 78 <-> 56 <-> 89

Do you want to continue (Type y or n)

y
Doubly Linked List Operations
1. insert at the beginning
2. insert at the end
3. insert at position
4. delete at position
5. check empty
6. get size
6
Size = 3

xxxvi
Doubly Linked List = 78 <-> 56 <-> 89

Do you want to continue (Type y or n)

xxxvii
WEEK-4
Experiment-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
a selected color. Initially there is no message shown.
Program :
package programs;
import javax.swing.*;
importjavax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
classTLightsextends JFrame implementsItemListener
{
public JLabel lb1, lb2;
public JRadioButton rb1, rb2, rb3;
public ButtonGroup bg;
public JPanel p, p1;
CheckboxGroup chboxGrp;
public TLights()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2, 1));
setSize(800, 400);
p = new JPanel(new FlowLayout());
p1 = new JPanel(new FlowLayout());
lb1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 60);
lb1.setFont(f); add(lb1); p.add(lb1);
add(p);
lb2 = new JLabel("Select Lights");
p1.add(lb2);
chboxGrp = new CheckboxGroup();
Checkbox rb1 = new Checkbox("Red Light", chboxGrp, true);
rb1.setBackground(Color.red);
p1.add(rb1);
rb1.addItemListener(this);
Checkbox rb2 = new Checkbox("Yellow Light", chboxGrp, true);
rb2.setBackground(Color.YELLOW);
p1.add(rb2);
rb2.addItemListener(this);
Checkbox rb3 = new Checkbox("Green Light", chboxGrp, true);
rb3.setBackground(Color.GREEN);
p1.add(rb3);
rb3.addItemListener(this);
add(p1);
setVisible(true);
}
publicvoiditemStateChanged(ItemEvent i)
{

xxxviii
Checkbox chk = chboxGrp.getSelectedCheckbox();
switch (chk.getLabel())
{
case"Red Light":
lb1.setText("STOP");
lb1.setForeground(Color.red);
break;
case"Yellow Light":
lb1.setText("Ready");
lb1.setForeground(Color.YELLOW);
break;
case"Green Light":
lb1.setText("GO");
lb1.setForeground(Color.GREEN);
break;
}
}
}
publicclass TrafficLights {
publicstaticvoid main(String[] args)
{
TLights a = new TLights();
}
}

OUTPUT:

xxxix
xl
xli
Experiment-8 :

Write a java program to create an abstract class named Shape that contains two integers
and an empty method named printArea(). Provide three classes named Rectangle,
Triangle and Circle such that each one of the classes extends the class Shape. Each one of
the classes contain only the method printArea( ) that prints the area of the given shape.
Program :
package programs;
publicclass AbstractShape {

publicstaticvoid main(String[] args) {

Rectangle rect = new Rectangle();


rect.printArea();
Triangle tri = new Triangle();
tri.printArea();
Circle cir = new Circle();
cir.printArea();
}

}
Abstract class Shape{
Int i = 1;
intj = 2;
abstractvoid printArea();
}
class Rectangle extends Shape{

@Override
void printArea() {
intarea = i * j;
System.out.println("The area of Rectangle is : "+area);

}
class Triangle extends Shape{
@Override
void printArea() {

intarea = (int) (0.5*i*j); // formula= 1/2(Base * Height)


System.out.println("The area of Triangle is : "+area);
}

}
class Circle extends Shape{

@Override
void printArea() {
intarea = (int) (3.14*i*i);

xlii
System.out.println("The area of Circle is : "+area);

New

package programs;
public class AbstractShape {

public static void main(String[] args) {

Rectangle rect = new Rectangle();


rect.printArea();
Triangle tri = new Triangle();
tri.printArea();
Circle cir = new Circle();
cir.printArea();
}

}
abstract class Shape{
int i = 1;
int j = 2;
abstract void printArea();
}
class Rectangle extends Shape{

void printArea() {
int area = i * j;
System.out.println("The area of Rectangle is : "+area);

}
class Triangle extends Shape{

void printArea() {

int area = (int) (0.5*i*j); // formula= 1/2(Base * Height)


System.out.println("The area of Triangle is : "+area);
}

}
class Circle extends Shape{

void printArea() {
int area = (int) (3.14*i*i);
System.out.println("The area of Circle is : "+area);

xliii
}

OUTPUT :

xliv
WEEK-5
Experiment-9:
Suppose that a table named Table.txt is stored in a text file. The first line in the file header
and the remaining lines correspond to row in the table. The elements are separated by
commas. Write a Java program to display the table using labels in grid layout.
Program :
package programs;

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Ta extends JFrame
{
public Ta()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600, 600);
GridLayout g = new GridLayout(0, 4);
setLayout(g);
try
{
FileInputStream fin = new FileInputStream("D://notepads/student.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 Label(i));
}
}
} catch (Exception ex) {
}
pack();
setVisible(true);
}
}
public class Table
{
public static void main(String[] args)
{
Ta a = new Ta();

xlv
}
}

OUTPUT :
First you have to create a notepad name student.txt and give some data separated by delimeter(,).
Then execute the program

xlvi
Experiment-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).
Question : What are adapter classes?
Program :
package programs;
import javax.swing.*;
import java.awt.*;
importjavax.swing.event.*;
import java.awt.event.*;
classMEventsextends JFrame implements MouseListener
{
JLabel l1;
public MEvents()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new FlowLayout());
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
l1.setAlignmentX(Component.CENTER_ALIGNMENT);
l1.setAlignmentY(Component.CENTER_ALIGNMENT);
add(l1);
addMouseListener(this);
setVisible(true);
}
publicvoid mouseExited(MouseEvent m)
{
l1.setText("Mouse Exited");
}
publicvoid mouseEntered(MouseEvent m)
{
l1.setText("Mouse Entered");
}
publicvoid mouseReleased(MouseEvent m)
{
l1.setText("Mouse Released");
}
publicvoid mousePressed(MouseEvent m)
{
l1.setText("Mouse Pressed");
}
publicvoid mouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
}
publicclass MouseEvents
{

xlvii
publicstaticvoid main(String[] args) {
MEventsa = newMEvents();
}

New

package programs;
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class MEvents extends JFrame implements MouseListener
{
JLabel l1;
public MEvents()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setLayout(new FlowLayout());
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
l1.setAlignmentX(Component.CENTER_ALIGNMENT);
l1.setAlignmentY(Component.CENTER_ALIGNMENT);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
l1.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
l1.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
l1.setText("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
}
public class MouseEvents
{
public static void main(String[] args)

xlviii
{
MEvents a = new MEvents();
}
}

OUTPUT :

xlix
WEEK-6

Experiment-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 :
package programs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
publicclass HashT
{
publicstaticvoid main(String[] args)
{
HashT ht = new HashT();
Hashtable<String, String>hashData =
ht.readFromFile("D://notepads/Hashtab.txt");
System.out.println("File data into Hashtable:\n"+hashData);
ht.printTheData(hashData, "cse");
ht.printTheData(hashData, "455");
ht.printTheData(hashData, "***");
}
privatevoid 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;

l
break;
} } } }
System.out.println("Input given:"+input);
if(output != null)
{
System.out.println("Data found in HashTable:"+output);
}
else {
System.out.println("Data not found in HashTable");
} }
private Hashtable<String, String>readFromFile(String fileName) {
Hashtable<String, String>hashData = new Hashtable<String, String>();
try {
File f = new File("D://notepads//"+fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;
while((line = br.readLine()) != null) {
String[] details = line.split("\t");
hashData.put(details[0], details[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); }
returnhashData;
} }

New
package programs;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;
public class HashT
{
public static void main(String[] args)
{
HashT ht = new HashT();
Hashtable<String, String>hashData =
ht.readFromFile("D://notepads/Hashtab.txt");
System.out.println("File data into Hashtable:\n"+hashData);
ht.printTheData(hashData, "cse");

li
ht.printTheData(hashData, "455");
ht.printTheData(hashData, "***");
}
private void printTheData(Hashtable<String, String>hashData, String input)
{
String output = null;
if(hashData != null)
{
Set<String>keys = hashData.keySet();
if(keys.contains(input))
{
output = hashData.get(input);
}
else
{
Iterator<String>iterator = keys.iterator();
while(iterator.hasNext()) {
String key = iterator.next();
String value = hashData.get(key);
if(value.equals(input))
{
output = key;
break;
} } } }
System.out.println("Input given:"+input);
if(output != null)
{
System.out.println("Data found in HashTable:"+output);
}
else {
System.out.println("Data not found in HashTable");
} }
private Hashtable<String, String>readFromFile(String fileName) {
Hashtable<String, String>hashData = new Hashtable<String, String>();
try {
File f = new File("D://notepads//"+fileName);
BufferedReader br = new BufferedReader(new FileReader(f));
String line = null;

lii
while((line = br.readLine()) != null) {
String[] details = line.split("\t");
hashData.put(details[0], details[1]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace(); }
return hashData;
} }

OUTPUT :
HashTab.txt
cse565
ece353
mech747

liii
Experiment-12 :
Write a Java program that correctly implements the producer – consumer problem
using the concept of inter thread communication.
Program :
package programs;

import java.util.LinkedList;
publicclass ProdCons
{
publicstaticvoid main(String[] args)
throws InterruptedException
{
// Object of a class that has both produce()
// and consume() methods
final PC pc = new PC();

// Create producer thread


Thread t1 = new Thread(new Runnable()
{
@Override
publicvoid run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

// Create consumer thread


Thread t2 = new Thread(new Runnable()
{
@Override
publicvoid run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

// Start both threads


t1.start();
t2.start();

liv
// t1 finishes before t2
t1.join();
t2.join();
}

// This class has a list, producer (adds items to list


// and consumber (removes items).
publicstaticclass PC
{
// Create a list shared by producer and consumer
// Size of list is 2.
LinkedList<Integer>list = new LinkedList<>();
intcapacity = 2;

// Function called by producer thread


publicvoid produce() throws InterruptedException
{
intvalue = 0;
while (true)
{
synchronized (this)
{
// producer thread waits while list
// is full
while (list.size()==capacity)
wait();

System.out.println("Producer produced-"
+ value);

// to insert the jobs in the list


list.add(value++);

// notifies the consumer thread that


// now it can start consuming
notify();

// makes the working of program easier


// to understand
Thread.sleep(1000);
}
}
}

// Function called by consumer thread


publicvoid consume() throws InterruptedException
{
while (true)
{
synchronized (this)
{
// consumer thread waits while list
// is empty
while (list.size()==0)
wait();

lv
//to retrive the ifrst job in the list
intval = list.removeFirst();

System.out.println("Consumer consumed-"
+ val);

// Wake up producer thread


notify();

// and sleep
Thread.sleep(1000);
}
}
}
}
}

OUTPUT :

lvi
WEEK-7
Experiment-13 :
Write a Java program to list all the files in a directory including the files present in all
its subdirectories.
Program :
package programs;
import java.io.File;
public class ListFiles {
static void RecursivePrint(File[] arr,intindex,intlevel)
{
// terminate condition
if(index == arr.length)
return;

// tabs for internal levels


for (inti = 0; i<level; i++)
System.out.print("\t");

// for files
if(arr[index].isFile())
System.out.println(arr[index].getName());

// for sub-directories
elseif(arr[index].isDirectory())
{
System.out.println("[" + arr[index].getName() + "]");

// recursion for sub-directories


RecursivePrint(arr[index].listFiles(), 0, level + 1);
}

// recursion for main directory


RecursivePrint(arr,++index, level);
}

// Driver Method
publicstaticvoid main(String[] args)
{
// Provide full path for directory(change accordingly)
String maindirpath = "D:\\notepads";

// File object
File maindir = new File(maindirpath);

if(maindir.exists() &&maindir.isDirectory())
{
// array for files and sub-directories
// of directory pointed by maindir
File arr[] = maindir.listFiles();

System.out.println("**********************************************");

lvii
System.out.println("Files from main directory : " + maindir);

System.out.println("**********************************************");

// Calling recursive method


RecursivePrint(arr,0,0);
}
}
}

OUTPUT :

lviii

You might also like