0% found this document useful (0 votes)
4 views55 pages

Java Programming Lab Manual

The Java Programming Lab Manual for 2021-2022 at Swami Vivekananda Institute of Technology outlines various programming exercises aimed at enhancing students' skills in Java, including GUI development, multithreading, and data structures. Each program includes objectives, descriptions, and sample code, along with instructions for using the Eclipse IDE. The manual also lists reference books and expected course outcomes related to Java programming competencies.

Uploaded by

killerspace66
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
4 views55 pages

Java Programming Lab Manual

The Java Programming Lab Manual for 2021-2022 at Swami Vivekananda Institute of Technology outlines various programming exercises aimed at enhancing students' skills in Java, including GUI development, multithreading, and data structures. Each program includes objectives, descriptions, and sample code, along with instructions for using the Eclipse IDE. The manual also lists reference books and expected course outcomes related to Java programming competencies.

Uploaded by

killerspace66
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 55

JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

SWAMI VIVEKANANDA INSTITUTE OF TECHNOLOGY

Mahbub College Campus, Secunderabad 500 003.

JAVA PROGRAMMING LABORATORY MANUAL

NAME OF THE STUDENT:…………………………………….…

ROLL NO :………………………………………………………………

BRANCH:……………………………..SECTION:…….……………

YEAR: …………………………SEMESTER:………………………..

FACULTY INCHARGE SIGNATURE

Page 1
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

B.TECH II Year II Sem. LTPC


0021

CS408PC: JAVA PROGRAMMING LAB


Course Objectives:

• To write programs using abstract classes.


• To write programs for solving real world problems using java collection frame work.
• To write multithreaded programs.
• To write GUI programs using swing controls in Java.
• To introduce java compiler and eclipse platform.
• To impart hands on experience with java programming.

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:

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.

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:

Write a Java program for the following:


Create a doubly linked list of elements.
Delete a given element from the above list.
Display the contents of the list after deletion.

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

for(j = 1; j<=i; j++){


if(i%j == 0)
count++;
else
continue;
}
if(count == 2)
System.out.print(i + " ");
} }}

Steps in writing and compiling the program in eclipse IDE

1. Click eclipse.exe file to start the IDE


2. Choose a Workspace Directory
Eclipse organizes projects by workspaces. A workspace is a group of related projects and
it is actually a directory on your computer.
3. Create a Java Project
To create a new Java project in Eclipse, go to File > New > Java Project. The New Java
Project wizard dialog appears let you specify configurations for the project. Give the
project name to be TEST.
4. To create a new Java class right click on the project and select New > Class from the
context menu. The New Java Class dialog appears, type the name of class as Test and
choose the option to generate the main() method. And click Finish. The Test class is
generated.
5. Type the program in the generated class.
6. Compile, Build and Run Your First Java Program
By default, Eclipse compiles the code automatically as you type. And it will report
compile errors in the Problems view if ant errors arises.
7. Now, let’s run the application. Click menu Run > Run (or press Ctrl + F11), Eclipse will
execute the application and show the output in the Console view.
OUTPUT :

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

public class Calculator extends JFrame implements ActionListener


{
String msg="";
int v1,v2,result,flag=0;
JTextField t1;
JButton b[]=new JButton[10];
JButton Add,Mul,Sub,Mod,Div,clear,Equal;
char op;
JPanel p1,p2;
JLabel l;
public Calculator()
{ super("Calculator");
setVisible(true);
setSize(340,300);

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);
}
}
}

Compile, Build and Run Your Java Program


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

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>*/

public class simpleApplet extends Applet{


public void init(){
setBackground(Color.green);
setForeground(Color.black);
}
public void paint(Graphics g)
{
g.drawString("a simple applet",45,50);
}
}

Compile, Build and Run Your Java Program


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.

Page 15
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

OUTPUT

Page 16
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

Develop an applet that receives an integer in one text field , and


Program No: 3(b) computes its factorial value and returns it in another text field , when
the button named ''compute'' is clicked

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+"");
} }}

Compile, Build and Run Your Java Program


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.

Page 18
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

OUTPUT

Page 19
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

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
Program No:4
throw a Number Format Exception. if Num2 were zero , the program would
throw an Arithmetic Exception. Display the exception in a message dialog
box.

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

/*<applet code="Division" width=200 height=200></applet>*/

public class Division extends Applet implements ActionListener{


TextField t1,t2,t3;
Button b1,b2;
Label l1,l2,l3;
String str;
public void init(){

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

Write a Java program that implements a multi-thread application that has


three threads. First thread generates random integer every 1 second and
Program No: 5 if the value is even, second thread computes the square f the number and
prints. If the value is odd, the third thread will print the value of cube of
the number.

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

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++)
{
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 mythread
{
public static void main(String[] args)
{
A a = new A();

Page 24
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

a.start();
}}

Compile, Build and Run Your Java Program


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
Main Thread and Generated Number is 52
New Thread 52 is EVEN and Square of 52 is: 2704

Main Thread and Generated Number is 8


New Thread 8 is EVEN and Square of 8 is: 64

Main Thread and Generated Number is 30


New Thread 30 is EVEN and Square of 30 is: 900

Main Thread and Generated Number is 33


New Thread 33 is ODD and Cube of 33 is: 35937

Main Thread and Generated Number is 82


New Thread 82 is EVEN and Square of 82 is: 6724

Test 2:
Main Thread and Generated Number is 14
New Thread 14 is EVEN and Square of 14 is: 196

Main Thread and Generated Number is 61


New Thread 61 is ODD and Cube of 61 is: 226981

Main Thread and Generated Number is 56


New Thread 56 is EVEN and Square of 56 is: 3136

Main Thread and Generated Number is 17


New Thread 17 is ODD and Cube of 17 is: 4913

Main Thread and Generated Number is 52


New Thread 52 is EVEN and Square of 52 is: 2704

Page 25
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

Write a Java program for the following:


Program No:6 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.

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;

class DoublyLinkedListImpl <E>


{

private Node head;


private Node tail;
private int size;

public DoublyLinkedListImpl() {
size = 0;
}

/* this class keeps track of each element information */


private class Node {
E element;
Node next;
Node prev;

Page 26
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

public Node(E element, Node next, Node prev) {


this.element = element;
this.next = next;
this.prev = prev;
}
}
/* returns the size of the linked list */
public int size() { return size; }

/* return whether the list is empty or not */


public boolean isEmpty() { return size == 0; }

/* adds element at the starting of the linked list */


public void addFirst(E element) {
Node tmp = new Node(element, head, null);
if(head != null ) {head.prev = tmp;}
head = tmp;
if(tail == null) { tail = tmp;}
size++;
System.out.println("adding: "+element);
}

/* adds element at the end of the linked list */


public void addLast(E element) {

Node tmp = new Node(element, null, tail);


if(tail != null) {tail.next = tmp;}
tail = tmp;
if(head == null) { head = tmp;}
size++;
System.out.println("adding: "+element);
}

/* this method walks forward through the linked list */


public void iterateForward(){

System.out.println("iterating forward..");
Node tmp = head;
while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.next;
}
}

/* this method walks backward through the linked list */


public void iterateBackward(){

System.out.println("iterating backword..");

Page 27
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

Node tmp = tail;


while(tmp != null){
System.out.println(tmp.element);
tmp = tmp.prev;
}
}

/* 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;
}

public static void main(String a[]){

DoublyLinkedListImpl<Integer> dll = new DoublyLinkedListImpl<Integer>();


dll.addFirst(10);
dll.addFirst(34);
dll.addLast(56);
dll.addLast(364);
dll.iterateForward();
System.out.println("Delete the First Element");
dll.removeFirst();
dll.iterateForward();
System.out.println("Delete the Last Element");
dll.removeLast();
dll.iterateBackward();
}
}

Compile, Build and Run Your Java Program


By default, Eclipse compiles the code automatically as you type. And it will report compile
errors in the Problems view if any errors arises.
Page 28
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

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:
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.*;

/*<applet code="TrafficLights1" width=300 height=200></applet>*/

public class TrafficLights1 extends JApplet implements


ItemListener{
JRadioButton rbut,gbut,ybut;
public void init(){
Container c=getContentPane();
c.setLayout(new FlowLayout());

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);
} }}

Compile, Build and Run Your Java Program


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

Page 32
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

Test: 3

Page 33
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

Write a Java program to create an abstract class named Shape that


contains two integers and an empty method named print Area (). Provide
Program No:8 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.

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

}
}

class rectangle extends shape{


rectangle(int a,int b){
super(a,b);
}
void area(){
System.out.println("The area of a Triangle is"+(x*y));
}
}

class circle extends shape{


circle(int a){
super(a,a);
}
void area(){
System.out.println("The area of a Circle is"+(3.14*x*x));
}
}
class figure{
public static void main(String[] args){
shape f;
triangle1 t=new triangle1(3,4);
f=t;
f.area();
rectangle r=new rectangle(5,6);
f=r;
f.area();
circle c=new circle(5);
f=c;
f.area();
}}

Compile, Build and Run Your Java Program


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
The area of a Triangle is6.0
The area of a Rectangle is30

Page 35
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

The area of a Circle is78.5

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

FileInputStream fin = new FileInputStream("D:\\jogarao\\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);
wclose w=new wclose();
addWindowListener(w);
}
}
public class TableData
{
public static void main(String[] args)
{
A a = new A();
}
}
class wclose extends WindowAdapter
{
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}

Compile, Build and Run Your Java Program


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.

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

/*<applet code="MouseEvents" width=600 height=300></applet>*/


public class MouseEvents extends Applet
{
String str;
public void init()
{
setForeground(Color.RED);
str="Welcome To Mouse Events";
addMouseListener(new MouseAdapter()
{
public void mouseEntered(MouseEvent me)
{
str="Mouse Just Entered applet Window";

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);
}}

Compile, Build and Run Your Java Program

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 class HashDemo {

public static void main(String[] args) {


HashDemo obj = new HashDemo();
obj.run();

}
public void run() {

String csvFile = "phone.txt";


BufferedReader br = null;

Page 43
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));


String line = "";
String cvsSplitBy = " ";
Hashtable code= new Hashtable();
Enumeration names;

try {

br = new BufferedReader(new FileReader(csvFile));


while ((line = br.readLine()) != null)
{

String[] cus = line.split(cvsSplitBy);

code.put(cus[0],cus[1] );

}
names = code.keys();

System.out.println("Phone book details are:");


while(names.hasMoreElements())
{
String str = (String) names.nextElement();

System.out.println(str + ": " + code.get(str));


}
System.out.println("enter the Customer name:");
String st=br1.readLine();

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");
}
}

Compile, Build and Run Your Java Program


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:

File: phone.txt

Phone book details are:

Rama: 123

Laxman: 789

Sita: 456

enter the Customer name:

Laxman

Laxman phone number is : 789

Done

Page 45
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

Write a Java program that correctly implements the producer – consumer


Program No: 12 problem using the concept of interthread communication.

Description:-

Inter-thread communication or Co-operation is all about allowing synchronized threads to


communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running


in its critical section and another thread is allowed to enter (or lock) in the same critical section
to be executed.It is implemented by following methods of Object class:

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.");
}}

Compile, Build and Run Your Java Program


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

Compile, Build and Run Your Java Program


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

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:

public class MyQuickSort {


private int array[];
private int length;
public void sort(int[] inputArr) {
if (inputArr == null || inputArr.length == 0) {
return;
}
this.array = inputArr;
length = inputArr.length;
quickSort(0, length - 1);
}
private void quickSort(int lowerIndex, int higherIndex)
{
int i = lowerIndex;
int j = higherIndex;
int pivot = array[lowerIndex+(higherIndex-lowerIndex)/2];
while (i <= j)
{
while (array[i] < pivot)
{
Page 51
JAVA PROGRAMMING LAB MANUAL 2021-2022 SVIT

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

for( pass = 0; pass < n; pass++ )


{
exch = 0;
for( i = 0; i < n-pass-1; i++ )
if(a[i]<a[i+1])
{ tmp = a[i];
a[i] = a[i+1];
a[i+1] = tmp;
exch++;
count++;
}
if( exch == 0 )
return; // sorting finished – return early
}
}
static void display( int a[] )
{
for( int i = 0; i < a.length; i++ )
System.out.print( a[i] + " " );
}
}

Compile, Build and Run Your Java Program


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:

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

You might also like