Java Programming Lab Manual
Java Programming Lab Manual
ROLL NO :………………………………………………………………
BRANCH:……………………………..SECTION:…….……………
YEAR: …………………………SEMESTER:………………………..
Page 1
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Program 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.
Program 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.
Program 3:
Program 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.
Page 2
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Program 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 6:
Program 7:
Write a Java program that simulates a traffic light. The program lets the user select one of three
lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate message
with “Stop” or “Ready” or “Go” should appear above the buttons in selected color. Initially,
there is no message shown.
Program 8:
Write a Java program to create an abstract class named Shape that contains two integers and
an empty method named print Area (). Provide three classes named Rectangle, Triangle, and
Circle such that each one of the classes extends the class Shape. Each one of the classes
contains only the method print Area () that prints the area of the given shape.
Program 9:
Suppose that a table named Table.txt is stored in a text file. The first line in the file is the
header, and the remaining lines correspond to rows in the table. The elements are separated by
commas. Write a java program to display the table using Labels in Grid Layout.
Program 10:
Write a Java program that handles all mouse events and shows the event name at the center of
the window when a mouse event is fired (Use Adapter classes).
Program 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
Page 3
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
name or phone number as input and prints the corresponding other value from the hash table
(hint: use hash tables).
Program 12:
Write a Java program that correctly implements the producer – consumer problem using the
concept of interthread communication.
Program 13:
Write a Java program to list all the files in a directory including the files present in all its
subdirectories.
Program 14:
Write a Java program that implements Quick sort algorithm for sorting a list of names in
ascending order
Program 15:
Write a Java program that implements Bubble sort algorithm for sorting in descending order
and also shows the number of interchanges occurred for the given set of integers.
REFERENCE BOOKS
1. Java for Programmers, P. J. Deitel and H. M. Deitel, 10th Edition Pearson education.
2. Thinking in Java, Bruce Eckel, Pearson Education.
3. Java Programming, D. S. Malik and P. S. Nair, Cengage Learning.
4. Core Java, Volume 1, 9th edition, Cay S. Horstmann and G Cornell, Pearson.
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.
Page 4
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
CONTENTS
Program Name of the program Page.no
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
1 can use auto suggestions, auto fill. Try code formatter and code 07
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 a grid
2 layout to arrange buttons for the digits and for the +, -,*, % 10
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 message.
3 b) Develop an applet in Java that receives an integer in one text field, 15
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 perform integer
4 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 20
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 application that
5 has three threads. First thread generates random integer every 1
second and if the value is even, second thread computes the square 23
of the number and prints. If the value is odd, the third thread will
print the value of cube of the number.
Write a Java program for the following:
6 Create a doubly linked list of elements. 26
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 program lets
7 the user select one of three lights: red, yellow, or green with radio
buttons. On selecting a button, an appropriate message with “Stop” 30
or “Ready” or “Go” should appear above the buttons in selected color.
Initially, there is no message shown.
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
8 each one of the classes extends the class Shape. Each one of the 34
Page 5
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
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. The first
9 line in the file is the header, and the remaining lines correspond to 36
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 shows the
10 event name at the center of the window when a mouse event is fired 39
(Use Adapter classes).
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 43
11 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 – 46
consumer problem using the concept of interthread communication.
13 Write a Java program to list all the files in a directory including the 49
files present in all its subdirectories.
14 Write a Java program that implements Quick sort algorithm for 51
sorting a list of names in ascending order
15 Write a Java program that implements Bubble sort algorithm for 54
sorting in descending order and also shows the number of
interchanges occurred for the given set of integers.
Page 6
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
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
Program No: 1 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 to Print Prime Nos. upto the given Number.
Description:-
To develop java program in eclipse IDE and get acquaint to the various menus in the IDE.
Here we are developing the program about prime number generation up to the given
number. To say a number is prime or not, we check the number of factors for that number,
If number is having only two factors(say 1 and itself) then we call that number is prime
number. Here we are using a for loop(to repeat single statement for multiple number of
times) and selection statement(if-else) to generate the list of prime numbers. To accept input
from keyboard we are using Scanner class from util package.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
import java.util.Scanner;
class Test{
public static void main(String args[]){
int x, count, j;
Scanner in = new Scanner(System.in);
System.out.print("Enter The Range to Generate a Series of Prime Numbers :");
x = in.nextInt();
System.out.println();
for(int i = 1; i<=x; i++){
count = 0;
Page 7
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Page 8
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Page 9
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Write a java program that works as a simple calculator .use grid layout to
arrange buttons for the digits and for the +,-,*,/,% operations. add a text
Program No: 2 field to display the result. Handle any possible exceptions like divided by
zero
Description:-
A GUI application can be designed either by using AWT or Swings. In this application we are
using swings components because swing components are lightweight components and output
is independent of the operating system. Here in this application we are using the components
like JButton,JTextField and have also used gridlayout to arrange the components. The
Container which weare using is JFrame.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Page 10
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
setResizable(false);
p1=new JPanel();
p2=new JPanel();
l=new JLabel("Calculator Application");
t1=new JTextField(20);
p2.setLayout(new GridLayout(2,1));
p2.add(l);
p2.add(t1);
GridLayout g1=new GridLayout(4,5);
p1.setLayout(g1);
for(int i=0;i<10;i++)
b[i]=new JButton(""+i);
Add=new JButton("+");
Sub=new JButton("-");
Mul=new JButton("*");
Div=new JButton("/");
Mod=new JButton("%");
clear=new JButton("Clear");
Equal=new JButton("=");
//add(t1,BorderLayout.NORTH);
for(int i=0;i<10;i++)
p1.add(b[i]);
p1.add(Add);
p1.add(Sub);
p1.add(Mul);
p1.add(Div);
p1.add(Mod);
p1.add(clear);
p1.add(Equal);
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);
Equal.addActionListener(this);
add(p1,BorderLayout.CENTER);
add(p2,BorderLayout.NORTH);
DoIt it=new DoIt();
addWindowListener(it);
}
public void actionPerformed(ActionEvent ae){
Page 11
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
String str=ae.getActionCommand();
flag=0;
char ch=str.charAt(0);
if(Character.isDigit(ch))
t1.setText(t1.getText()+str);
else if(str.equals("+")){
v1=Integer.parseInt(t1.getText());
op='+';
t1.setText("");
}
else if(str.equals("-")){
v1=Integer.parseInt(t1.getText());
op='-';
t1.setText("");
}
else if(str.equals("*")){
v1=Integer.parseInt(t1.getText());
op='*';
t1.setText("");
}
else if(str.equals("/")){
v1=Integer.parseInt(t1.getText());
op='/';
t1.setText("");
}
else if(str.equals("%")){
v1=Integer.parseInt(t1.getText());
op='%';
t1.setText("");
}
else if(str.equals("Clear")){
t1.setText("");
}
else{
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=='/')
try
{
Page 12
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
result=v1/v2;
}catch(Exception e)
{
flag=1;
}
else if(op=='%')
result=v1%v2;
if(flag==1)
t1.setText(""+"Division by Zero Error");
else
t1.setText(""+result);
}
}
public static void main(String args[])
{
new Calculator();
}
}
class DoIt extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
}
Page 13
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Page 14
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Program No: 3(a) Develop an applet in java that displays a simple message
Description:-
Applets are compiled java programs that are run using AppletViewer or through any browser
that supports. it can display graphics, sounds, accept user input and manipulate data just like
any program. A separate HTML file should be created with details as name of the class file ,
location of the class and the applet position on the web page. Applet inherit the properties of
the panel object and the applet class attributes.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
import java.awt.*;
import java.applet.*;
/* <applet code="simpleApplet" width=200 height=100></applet>*/
Page 15
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
OUTPUT
Page 16
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Description:-
when a HTML(HyperText Markup Language) page wants to communicate with the user on
internet, it can use a special java program called applet to communicate and respond to the
user. The user can interact by typing some details or by clicking the components available in the
applet program. The program then process and display the results. We can understand an
applet as a java byte code embedded in a HTML page, generally for the purpose of achieving
communication with the user.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="FactDemo" width=300 height=200></applet>*/
public class FactDemo extends Applet implements ActionListener{
JTextField t1,t2;
JButton b1,b2;
JLabel l1,l2,l3;
JPanel p;
String str;
public void init(){
p=new JPanel();
p.setLayout(new GridLayout(3,2));
t1=new JTextField(10);
t2=new JTextField(10);
b1=new JButton("compute");
b2=new JButton("clear");
l1=new JLabel("Enter a Number");
l2=new JLabel("Factorial");
Page 17
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
p.add(l1);
p.add(t1);
p.add(l2);
p.add(t2);
p.add(b1);
p.add(b2);
add(p);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
str=ae.getActionCommand();
if(str.equals("clear")){
t1.setText("");
t2.setText("");
}
else{
int n=Integer.parseInt(t1.getText());
int fact=1;
for(int i=1;i<=n;i++)
fact *=i;
t2.setText(fact+"");
} }}
Page 18
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
OUTPUT
Page 19
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Description:-
In this application we are using two swing components(JTextField, JButton) to design the GUI
interface. The input data is provided by means of two TextFields. Generally When a button
is clicked it generates an event called ActionEvent. By default all components are not able to
listen about the event. Hence, to make the Button to listen about the event we are adding
listener called ActionListener to the Button. ActionListener is an interface. This interface
consists of only one abstract method, and this method must be implemented by the
programmer so, that a Button can perform the action when it is clicked.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
Page 20
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
b1=new Button("Divide");
b2=new Button("clear");
l1=new Label("Num1");
l2=new Label("Num2");
l3=new Label("Result");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae){
str=ae.getActionCommand();
if(str.equals("clear")){
t1.setText("");
t2.setText("");
t3.setText("");
}
else{
try{
int n=Integer.parseInt(t1.getText());
int m=Integer.parseInt(t2.getText());
int r=n/m;
t3.setText(""+r);
}
catch(NumberFormatException e){
JOptionPane.showMessageDialog(null,"Only Integers Should Be Entered");
}
catch(ArithmeticException r){
JOptionPane.showMessageDialog(null,"Divide By Zero Not Possible");
}
}
}
}
Page 21
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
OUTPUT
Test-1 Test-2
Page 22
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Description:-
A thread represents a separate path of execution of a group of statements. In java program if
we write a group of statements, then these statements are executed by JVM one by one . This
execution is called a thread, because JVM uses a thread to execute these statements. This
means that in every java program , there is always a thread running internally. This thread is
used by JVM to execute the program statements. We can also create a thread in one of the
two ways
1. Extends from Thread class
2. Implementing from the runnable interface.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
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);
}
}
Page 23
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Page 24
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
a.start();
}}
OUTPUT:
Test:1
Main Thread and Generated Number is 52
New Thread 52 is EVEN and Square of 52 is: 2704
Test 2:
Main Thread and Generated Number is 14
New Thread 14 is EVEN and Square of 14 is: 196
Page 25
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Description:-
A doubly-linked list is a linked data structure that consists of a set of sequentially linked records
called nodes. Each node contains two fields, called links, that are references to the previous and
to the next node in the sequence of nodes. The beginning and ending nodes previous and next
links, respectively, point to some kind of terminator, typically a sentinel node or null, to
facilitate traversal of the list. If there is only one sentinel node, then the list is circularly linked
via the sentinel node. It can be conceptualized as two singly linked lists formed from the same
data items, but in opposite sequential orders.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
import java.util.NoSuchElementException;
public DoublyLinkedListImpl() {
size = 0;
}
Page 26
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
System.out.println("iterating forward..");
Node tmp = head;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.next;
}
}
System.out.println("iterating backword..");
Page 27
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
/* this method removes element from the start of the linked list */
public E removeFirst() {
if (size == 0) throw new NoSuchElementException();
Node tmp = head;
head = head.next;
head.prev = null;
size--;
System.out.println("deleted: "+tmp.element);
return tmp.element;
}
/* this method removes element from the end of the linked list */
public E removeLast() {
if (size == 0) throw new NoSuchElementException();
Node tmp = tail;
tail = tail.prev;
tail.next = null;
size--;
System.out.println("deleted: "+tmp.element);
return tmp.element;
}
OUTPUT:
adding: 10
adding: 34
adding: 56
adding: 364
iterating forward..
34
10
56
364
Delete the First Element
deleted: 34
iterating forward..
10
56
364
Delete the Last Element
deleted: 364
iterating backword..
56
10
Page 29
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
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.
Program No: 7 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.
Description:-
To develop this application we have used JRadioButton component, and we have selected
the container to be JApplet. To create visual representation of traffic pole in program, we
have taken the help of graphics class object which is parameter object of paint method. On
selecting one of three radiobuttons its respective color must be displayed in the traffic pole
with the name of the color. For this we have used the ItemEvent on all the three radiobuttons.
The corresponding listener for the ItemEvent is ItemListener which has only one abstract
method itemStateChanged that was implemented in the program.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Page 30
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
rbut=new JRadioButton("Red",false);
gbut=new JRadioButton("Green",false);
ybut=new JRadioButton("Yellow",false);
ButtonGroup gp=new ButtonGroup();
gp.add(rbut);
gp.add(ybut);
gp.add(gbut);
c.add(rbut);
c.add(ybut);
c.add(gbut);
rbut.addItemListener(this);
ybut.addItemListener(this);
gbut.addItemListener(this);
}
public void itemStateChanged(ItemEvent ie){
repaint();
}
public void paint(Graphics g)
{
g.drawRect(10,10,40,100);
g.drawRect(25,110,10,40);
g.fillRect(10,10,40,100);
g.fillRect(25,110,10,40);
g.drawOval(17,17,25,25);
g.drawOval(17,50,25,25);
g.drawOval(17,80,25,25);
g.fillOval(17,17,25,25);
g.fillOval(17,50,25,25);
g.fillOval(17,80,25,25);
if(rbut.isSelected()){
g.setColor(Color.red);
g.fillOval(17,22,25,25);
g.drawString("Stop",20,22);
}
else if(gbut.isSelected()){
g.setColor(Color.green);
g.fillOval(17,80,25,25);
g.drawString("Go",22,80);
}
else if(ybut.isSelected()){
g.setColor(Color.orange);
g.fillOval(17,50,25,25);
g.drawString("Ready",13,50);
Page 31
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
}
else {
g.setColor(Color.black);
g.fillOval(17,17,25,25);
g.fillOval(17,50,25,25);
g.fillOval(17,80,25,25);
} }}
OUTPUT
Test: 1 Test : 2
Page 32
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Test: 3
Page 33
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Description:-
An abstract class is a class that contains 0 or more abstract methods. An abstract method is a
method without method body. An abstract method is written when same method has to
perform different tasks depending on the object calling it. For abstract class an object cannot
be created but we can create a reference to it. Java language uses a principle called “A super
class reference variable can refer to a subclass object” by using this principle we can achieve
run-time polymorphism. In this program we have used this principle.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
abstract class shape{
int x,y;
shape(int a,int b){
x=a;
y=b;
}
abstract void area();
}
class triangle1 extends shape{
triangle1(int a,int b){
super(a,b);
}
void area(){
System.out.println("The area of a Triangle is"+(0.5*x*y));
Page 34
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
}
}
OUTPUT
The area of a Triangle is6.0
The area of a Rectangle is30
Page 35
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
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
Program No: 9 table. The elements are separated by commas. Write a java program to
display the table using Labels in Grid Layout.
Description:-
Streams facilitate transporting data from one place to another. Different streams are needed
to send or receive data through different sources such as keyboard, we need a stream and to
send data to a file, we need another stream. Without streams, it is not possible to move data in
java. FileInputStream is useful to read from a file in the form of sequence of bytes. It is possible
to read data from a text file using FileInputStream.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
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()
{
super(“Table Data”);
setSize(600, 600);
GridLayout g = new GridLayout(0, 3);
setLayout(g);
try
{
Page 36
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Page 37
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
OUTPUT:
Page 38
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Write a Java program that handles all mouse events and shows the event
Program No: 10 name at the center of the window when a mouse event is fired (Use
Adapter classes).
Description:-
The process of changing the state of the object is called event. Generally a component
cannot listen about the event has occurred. To make the component to know about the
event we add listener to the component. Whenever an event is occurred it delegates the
event to the listener to handle the event and provide the action. In java language all listener
are interfaces. To provide the action for the event we have to override all the methods of
the interface. The event raised(mousemoved, mousedragged, mousecliked etc) by the mouse
is called MouseEvent and the corresponding listeners are MouseMotionListener,
MouseLitener.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
Page 39
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
repaint();
}
public void mouseClicked(MouseEvent me)
{
str="Mouse Clicked";
repaint();
}
public void mouseExited(MouseEvent me)
{
str="Mouse Exited";
repaint();
}
public void mousePressed(MouseEvent me)
{
str="Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent me)
{
str="Mouse Released";
repaint();
}
});
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseDragged(MouseEvent me)
{
str="Mouse Dragged";
repaint();
}
public void mouseMoved(MouseEvent me)
{
str="Mouse Moved";
repaint();
}
});
}
public void paint(Graphics g)
{
g.drawString(str,200,150);
}}
Page 40
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
By default, Eclipse compiles the code automatically as you type. And it will report compile
errors in the Problems view if any errors arises.
Running the java application
Click menu Run > Run (or press Ctrl + F11), Eclipse will execute the application and show the
output in the Console view.
OUTPUT
TEST:1
Test:2
Test 3:
Page 41
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Test:4
Page 42
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
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
Program No 11 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).
Description:-
Java Hashtable class implements a hashtable, which maps keys to values. It inherits Dictionary
class and implements the Map interface.
The important points about Java Hashtable class are:
1. A Hashtable is an array of list. Each list is known as a bucket. The position of bucket is
identified by calling the hashcode() method. A Hashtable contains values based on the
key.
2. It contains only unique elements.
3. It may have not have any null key or value.
4. It is synchronized.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
import java.io.*;
import java.util.*;
}
public void run() {
Page 43
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
try {
code.put(cus[0],cus[1] );
}
names = code.keys();
names = code.keys();
while(names.hasMoreElements())
{
String str1 = (String) names.nextElement();
if(str1.equals(st))
System.out.println(str1 + " phone number is : " + code.get(str1));
}
}
catch (Exception e)
{
e.printStackTrace();
}
Page 44
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
System.out.println("Done");
}
}
OUTPUT:
File: phone.txt
Rama: 123
Laxman: 789
Sita: 456
Laxman
Done
Page 45
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Description:-
o wait()
o notify()
o notifyAll()
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
if(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
Page 46
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
return n;
}
synchronized void put(int n) {
if(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 {
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();
Page 47
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}}
OUTPUT:
Press Control-C to stop.
Put: 0
Got: 0
Put: 1
Got: 1
Put: 2
Got: 2
Put: 3
Got: 3
Put: 4
Got: 4
Put: 5
Got: 5
Put: 6
Got: 6
Put: 7
Got: 7
Page 48
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Write a Java program to list all the files in a directory including the files
Program No:13 present in all its subdirectories.
Description:-
File class of java.io package provides some methods to know the properties of a file or a
directory. First of all we should create the File class object by passing the filename or directory
name to it.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
import java.io.*;
class test
{
public void list1(String directoryName){
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isFile()){
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()){
list1(file.getAbsolutePath());
}
}
}
public static void main(String args[])
{
test t=new test();
t.list1("E:\\Lab Index");
}
}
Page 49
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
OUTPUT
D:\>javac test.java
D:\>java test
E:\Lab Index\CPP A.docx
E:\Lab Index\IT B\CPP B.docx
E:\Lab Index\IT B\CPP.xlsx
E:\Lab Index\IT B\ITWS B.docx
E:\Lab Index\IT B\ITWS.xlsx
E:\Lab Index\IT B\JAVA B.docx
E:\Lab Index\IT B\JAVA.xlsx
E:\Lab Index\ITWS.docx
E:\Lab Index\IWS A.docx
E:\Lab Index\JAVA A.docx
E:\Lab Index\New Microsoft Office Word Document.docx
E:\Lab Index\ravali mail id.txt
Page 50
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Program No: 14 Write a Java program that implements Quick sort algorithm for sorting a list
of names in ascending order
Description:-
QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and partitions the
given array around the picked pivot. There are many different versions of quickSort that pick
pivot in different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
i++;
}
while (array[j] > pivot)
{
j--;
}
if (i <= j)
{
exchangeNumbers(i, j);
i++;
j--;
}
}
if (lowerIndex < j) quickSort(lowerIndex, j);
if (i < higherIndex) quickSort(i, higherIndex);
}
private void exchangeNumbers(int i, int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String args[])
{
MyQuickSort sorter = new MyQuickSort();
int[]input= {24,2,45,20,56,75,2,56,99,53,12};
sorter.sort(input);
for(int i:input)
{
System.out.print(i);
System.out.print(" ");
}
}
}
Page 52
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
OUTPUT:
Page 53
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
Write a Java program that implements Bubble sort algorithm for sorting
Program No: 15 in descending order and also shows the number of interchanges
occurred for the given set of integers.
Description:-
Bubble Sort is an algorithm which is used to sort N elements that are given in a memory for eg:
an Array with N number of elements. Bubble Sort compares all the element one by one and sort
them based on their values. It is called Bubble sort, because with each iteration the largest
element in the list bubbles up towards the last place, just like a water bubble rises up to the
water surface.
Sorting takes place by stepping through all the data items one-by-one in pairs and comparing
adjacent data items and swapping each pair that is out of order.
Hardware:
Processor : intel P4 3.0 GH
Motherboard : intel 915 GV chipset
RAM : 2 GB DDR2
HardDisk : 80GB HDD SATA
Software Used:
Operating System : Ubuntu 14.04.4
Java version : JDK1.7.0
Eclipse IDE 1.6
Program:
class BubbleSort
{
static int count;
public static void main(String[] args)
{
int[] arr = { 49, 27, 65, 37, 15, 75, 63, 60 };
System.out.print("\n Unsorted array: ");
display( arr );
bSort( arr );
System.out.print("\n Sorted array: ");
display( arr );
System.out.println("\n No. Of interchanges are "+count);
}
static void bSort(int[] a)
{
int i, pass, exch, n = a.length;
int tmp;
Page 54
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT
OUTPUT:
Unsorted array: 49 27 65 37 15 75 63 60
Sorted array: 75 65 63 60 49 37 27 15
No. Of interchanges are 16
Page 55