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

IT Java Programming Lab Manual

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

IT Java Programming Lab Manual

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

Department of IT Lab Manual

AURORA’S TECHNOLOGICAL & RESEARCH INSTITUTE


Parvathapur, Uppal, Hyderabad-98

Java Programming Lab

LAB MANUAL
B. Tech – II Year - II Semester

R18 Regulation

NAME: __________________________________________

ROLL NO: __________________________________________

BRANCH: ________________________________________

DEPARTMENT OF INFORMATION TECHNOLOGY

Aurora’s Technological & Research Institute 1


Department of IT Lab Manual

INDEX
Sl.no Contents Page no

1 Preface 3
2 Objective and Relevance 3
3 Outcomes 3
4 Code of Conduct 4
5 List of Experiments 5
6 Syllabus analysis 7
7 Session Plan 10
8 Operating Environment 13
9 Experiment Write Up 13

9.1.1 Program to check the given no is prime or not 12


9.1.2 Develop simple calculator using Grid Layout 14
9.1.3.1 Develop an applet in java to display simple message 20
9.1.3.2 Develop an applet in java for computing factorial 22
9.1.4 Create a user interface to perform Integer Division 24
9.1.5 Implement a multi-threaded application 27
9.1.6 Implement doubly linked list to perform various operations 30
9.1.7 Write a java program that simulates a traffic light 37
9.1.8 Implement abstract class concept for shape class 40
9.1.9 Write a java program to display table using lables in grid layout 43
9.1.10 Write a java program that handles all mouse events 47
9.1.11 Implement the hash table concept by stroing key value pair 49
9.1.12 Implement the producer- consumer Problem 52
9.1.13 Write a program to list all files in a directory and its sub directories 56
9.1.14 Implement quick sort algorithm for sorting numbers in ascending order 58
9.1.15 Implement Bubble sort algorithm for sorting numbers in descending order 60

Aurora’s Technological & Research Institute 2


Department of IT Lab Manual

1. PREFACE

This laboratory manual is prepared by the Department of Information Technology for Java
Programming laboratory. This lab manual can be used as instructional book for students, staff and
instructors to assist in performing and understanding the experiments. In this manual, experiments as
per the college syllabus are described. This manual will be available in electronic form from
College’s official website, for the betterment of students.

2. OBJECTIVE AND RELEVANCE

 To understand Object Oriented Programming concepts and apply them in problem solving.
 To learn the basics of java concepts and GUI based programming.
 To write programs using abstract classes.
 To write programs for solving real world problems using java collection frame work.
 To write multithreaded programs.
 To introduce java compiler and eclipse platform.

3. OUTCOMES

Upon completion of this course, students would be able to:


 Understand the concept of OOP as well as the purpose and usage principles of inheritance,
polymorphism, encapsulation and method overloading.
 Identify classes, objects, members of a class and the relationships among them needed for a
specific problem.
 Create Java application programs using sound OOP practices (e.g., interfaces and APIs) and
proper program structuring (e.g., by using access control identifies, automatic documentation
through comments, error exception handling)
 Develop programs using the Java Collection API as well as the Java standard class library.
 Should get the ability to extend his/her knowledge of java programming further on his her
own.

Aurora’s Technological & Research Institute 3


Department of IT Lab Manual

4. CODE OF CONDUCT

 Students should report to the concerned lab as per the time table.

 Students who turn up late to the labs will in no case be permitted to do the program schedule for the day.

 After completion of the program, certification of the concerned staff in-charge in the observation book is
necessary.

 Student should bring a notebook of 100 pages and should enter the readings/observations into the
notebook while performing the experiment.

 The record of observations along with the detailed experimental procedure of the experiment in the
immediate last session should be submitted and certified staff member in-charge.

 Students should be present in the labs for total scheduled duration

 Students are required to prepare thoroughly to perform the experiment before coming to laboratory

Aurora’s Technological & Research Institute 4


Department of IT Lab Manual

5. LIST OF EXPERIMENTS

1. Use Eclipse or Net bean platform and acquaint with the various menus. Create a test project, add a
test class, and run it. See how you can use auto suggestions, auto fill. Try code formatter and code
refactoring like renaming variables, methods, and classes. Try debug step by step with a small
program of about 10 to 15 lines which contains at least one if else condition and a for loop.

2. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the
digits and for the +, -,*, % operations. Add a text field to display the result. Handle any possible
exceptions like divided by zero.

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


b) Develop an applet in Java that receives an integer in one text field, and computes its factorial
Value and returns it in another text field, when the button named “Compute” is clicked.

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

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

6. Write a Java program for the following:

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.

7. Write a Java program that simulates a traffic light. The program lets the user select one of three
lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate message with
“Stop” or “Ready” or “Go” should appear above the buttons in selected color. Initially, there is no
message shown.

8. Write a Java program to create an abstract class named Shape that contains two integers and an
empty method named print Area (). Provide three classes named Rectangle, Triangle, and Circle such
that each one of the classes extends the class Shape. Each one of the classes contains only the method
print Area () that prints the area of the given shape.

9. Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header,
and the remaining lines correspond to rows in the table. The elements are separated by commas.
Write a java program to display the table using Labels in Grid Layout.

Aurora’s Technological & Research Institute 5


Department of IT Lab Manual

10. Write a Java program that handles all mouse events and shows the event name at the center of the
window when a mouse event is fired (Use Adapter classes).

11. Write a Java program that loads names and phone numbers from a text file where the data is
organized as one line per record and each field in a record are separated by a tab (\t). It takes a name
or phone number as input and prints the corresponding other value from the hash table (hint: use hash
tables).

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

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

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

15. Write a Java program that implements Bubble sort algorithm for sorting in descending order and
also shows the number of interchanges occurred for the given set of integers.

Aurora’s Technological & Research Institute 6


Department of IT Lab Manual

6. SYLLABUS ANALYSIS

Week Text / Reference Page Nos


S.No. Name of the Experiment Unit No.
No. Book

Basic Programs Which UNIT-I T1:3.2-3.12


R2:3.6
1 1 contains at least one If
else and for loop
Write a java program that UNIT-V T1:17.3
works as a simple R4:14.11
2 2 calculator. Use grid lay
out to arrange buttons for
digits and operators
Develop an applet in java UNIT-V T1:15
that displays simple R4:12.2,12.5
R2:8.2
message. Develop an
3 3 applet that receives
integer and returns
factorial value when
button compute is clicked.
Write a java program that UNIT-V T1:18.1-18.2
creates User Interface to R4:15.5
4 4 perform integer divisions.
Display the exception in a
message dialogue box.
Write a java program that UNIT-III T1:10.12
implements multithreaded R4:7.3
5 5
application. That created 3
threads.
Write a java program to
create doubly linked list
of elements. Delete a
6 6 given element from the
above list and display
contents of the list after
deletion.
Write a java program that
simulates traffic light. The UNIT-V
T1:17.2
program lets user select
one of three lights: red,
yellow, or green with
7 7
radio button. On selecting
appropriate message with
“stop” or “ready” or “Go”
should appear above the
buttons in selected color.

Aurora’s Technological & Research Institute 7


Department of IT Lab Manual

Write a java program to UNIT-I T1:7.9-7.10


create abstract class
named shape that contain
empty method named
printArea(). Provide three
8 8 classes named rectangle,
triangle and circle. Each
one of the class contain
method printArea() that
prints the area of the
given shape.
Write a java program to UNIT-V R4:14.11
9 9 display the table using
labels in Grid Layout.
Write a java program that UNIT-V T1:17.3
handles mouse events and R4:14
show the event name at
10 10
the center of the window
when mouse event is
fired.
Write a java program that UNIT-IV T1:17
loads names and phone
numbers from a text file.
11 11
Print the corresponding
other value from hash
table.
Write a java program that UNIT-III T1:12.7-12.9
implements the producer- R2:6.5
12 12 consumer using concept
of interthread
communication
Write a java program to UNIT-II T1:19
list all the files in a
13 13 directory including the
files present in all its
subdirectories
Implement a Quick sort
algorithm for sorting a list
14 14
of names in ascending
order
Implement a Bubble sort
algorithm for sorting in
descending order and also
15 15
shows the number of
interchanges occurred for
the given set of integers.

Aurora’s Technological & Research Institute 8


Department of IT Lab Manual

7. SESSION PLAN
S. No. Week No. Unit as per Activity Remarks
Syllabus
Introduction PREREQUISITE
1 1 UNIT-I Basic java programs

UNIT-II Write a java program that JNTUH


2 2 works as a simple
calculator. Use grid lay out
to arrange buttons for digits
and operators
UNIT-V Develop an applet in java JNTUH
3 3 that displays simple
message. Develop an applet
that receives integer and
returns factorial value when
button compute is clicked.
UNIT-V Write a java program that JNTUH
4 4 creates User Interface to
perform integer divisions.
Display the exception in a
message dialogue box.

5 5 UNIT-III Write a java program that JNTUH


implements multithreaded
application. That created 3
threads.

Write a java program to JNTUH


6 6 create doubly linked list of
elements. Delete a given
element from the above list
and display contents of the
list after deletion.
Write a java program that JNTUH
7 7 simulates traffic light. The
UNIT-V program lets user select one
of three lights: red, yellow,
or green with radio button.
On selecting appropriate
message with “stop” or
“ready” or “Go” should
appear above the buttons in
selected color.
UNIT-I Implement a abstract class JNTUH

Aurora’s Technological & Research Institute 9


Department of IT Lab Manual

8 8 which contain empty


method named printArea().
Provide three classes named
rectangle, triangle and
circle. Each one of the class
contain method printArea()
that prints the area of the
given shape.
Write a java program to JNTUH
9 9 UNIT-V display the table using
labels in Grid Layout.
10 10 UNIT-V Write a java program that JNTUH
handles mouse events and
show the event name at the
center of the window when
mouse event is fired.
11 11 UNIT-iV JNTUH
Write a java program that
loads names and phone
numbers from a text file.
Print the corresponding
other value from hash table.
12 12 UNIT-III Implement the producer- JNTUH
consumer using concept of
interthread communication.
13 13 Write a program to list all JNTUH
the files in a directory
including the files present in
all its subdirectories
14 14 Implement Quick algorithm JNTUH
to sort names in ascending
order
15 15 Implement Bubble sort JNTUH
algorithm to sort integer
number in descending order

Aurora’s Technological & Research Institute 10


Department of IT Lab Manual

8. OPERATING ENVIRONMENT

Hardware
No. of System : 60(IBM)
Processor : PIV 1.67 GHZ
RAM : 512 MB
Hard Disk : 40 GB
Software
Operating System : Window XP
IDE : JDK 1.7 and Eclicpse or Net Beans

Aurora’s Technological & Research Institute 11


Department of IT Lab Manual

9. EACH EXPERIMENT WRITE UP

EXPERIMENT 1:

OBJECTIVE:

To debug step by step with small program of about 10 to 15 lines which contains at least one
if else condition and a for loop.

PROGRAM LOGIC:

1. Start the program


2. Create a class with the name “Testp‟.
3. Read n values from keyboard using a Scanner class.
4. Find the (n % i == 0) using dynamic initialization
5. Check the (n % i == 0) value using if condition.

PROCEDURE:

To execute a java program we require setting a class path:


C:\set path= C:\Program Files\Java\ JDK1.7\bin;.;
C:\javac Testp.java
C:\java Testp

SOURCE CODE
Import java.util.*;

public class Testp {


public static void main(String[] args)
{
System.out.println("Welcome To Aurora’s Technological & Research stitute");
System.out.println("--------Prime Number--------");
Scanner sc = new Scanner(System.in);
System.out.println("Enter valid Number");
int n = sc.nextInt();

int c = 0;
for (inti = 1; i<= n; i++)

Aurora’s Technological & Research Institute 12


Department of IT Lab Manual

if (n % i == 0)
{
c++;
}
}
if (c == 2)
{
System.out.println(n + "is Prime Number");
}
else
{
System.out.println(n + "is not Prime Number");
}
}
}
EXPECTED OUTPUT:
run:
Welcome To Aurora’s Technological & Research Institute
--------Prime Number--------
Enter valid Number
23
23is Prime Number
BUILD SUCCESSFUL (total time: 11 seconds)

Aurora’s Technological & Research Institute 13


Department of IT Lab Manual

EXPERIMENT 2:

OBJECTIVE:
To develop a program that works as simple calculator .Uses grid layout to arrange buttons for
the digits and for the +,-,*,% operations. Add text field to display the results, Handle any
possible exceptions like divide by zero.

RESOURCES:

JDK1.7is required, 1GB RAM, Hard Disk 80 GB.

PROGRAM LOGIC:

 Start the program


 Create a class with the name „A‟ extends JFrame implements ActionListener.
 Declare the JButton ,JTextField ,JPanel variables.
 Add listener to each button and to the layout.
 Add Text Field to display the result.
 Handle any Exceptions like divide by zero.

PROCEDURE:

To execute a java program we require setting a class path:


1.C:\set path= C:\Program Files\Java\ JDK1.7\bin;.;
2.C:\javac A.java
3.C:\java A

SOURCE CODE:

importjavax.swing.*;
importjavax.swing.event.*;
importjava.awt.*;
importjava.awt.event.*;

class A extends JFrame implements ActionListener {


public JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16; public
JTextField tf1;

Aurora’s Technological & Research Institute 14


Department of IT Lab Manual

publicJPanel p;

public String v = "";


public String v1 = "0";
public String op = "";

public A() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setSize(400, 400);
p = new JPanel(new FlowLayout());
tf1 = new JTextField(10); p.add(tf1);
add(p);

setLayout(new GridLayout(0, 3));


b1 = new JButton("1");
b1.addActionListener(this);
add(b1);
b2 = new JButton("2"); b2.addActionListener(this); add(b2);
b3 = new JButton("3"); b3.addActionListener(this); add(b3);
b4 = new JButton("4"); b4.addActionListener(this); add(b4);
b5 = new JButton("5"); b5.addActionListener(this); add(b5);
b6 = new JButton("6"); b6.addActionListener(this); add(b6);
b7 = new JButton("7"); b7.addActionListener(this); add(b7);
b8 = new JButton("8"); b8.addActionListener(this); add(b8);
b9 = new JButton("9"); b9.addActionListener(this); add(b9);
b10 = new JButton("0"); b10.addActionListener(this); add(b10);
b11 = new JButton("+"); b11.addActionListener(this); add(b11);
b12 = new JButton("-"); b12.addActionListener(this); add(b12);
b13 = new JButton("*"); b13.addActionListener(this); add(b13);
b14 = new JButton("/"); b14.addActionListener(this); add(b14);
b16 = new JButton("%"); b16.addActionListener(this); add(b16);
b15 = new JButton("="); b15.addActionListener(this); add(b15);
setVisible(true); }
public void actionPerformed(ActionEventae)
{
String b = ae.getActionCommand();
switch (b)
{
Aurora’s Technological & Research Institute 15
Department of IT Lab Manual

case "1":
{
v = v + "1"; tf1.setText(v);
}
break;
case "2":
{
v = v +"2";
tf1.setText(v);
}
break;
case "3":
{
v = v + "3";
tf1.setText(v); }
break;
case "4":
{
v = v + "4";
tf1.setText(v); }
break;
case "5":
{
v = v + "5";
tf1.setText(v);
}
break;
case "6":
{
v = v + "6";
tf1.setText(v);
}
break;
case "7":
{
v = v + "7";
tf1.setText(v);
}
break;
Aurora’s Technological & Research Institute 16
Department of IT Lab Manual

case "8":
{
v = v + "8";
tf1.setText(v);
}
break;
case "9":
{
v = v + "9"; tf1.setText(v);
}
break;
case "0":
{
v = v + "0";
tf1.setText(v);
}
break;
case "+":
{
op = "+";
v1 = tf1.getText(); v = "";
}
break;
case "-":
{
op = "-";
v1 = tf1.getText();
v = "";
}
break;
case "*":
{
op = "*";
v1 = tf1.getText();
v = "";
}
break;
case "/":
{
Aurora’s Technological & Research Institute 17
Department of IT Lab Manual

op = "/";
v1 = tf1.getText(); v = "";
}
break;
case "%":

{
op = "%";
v1 = tf1.getText();
v = "";
}
break; case "=":
{
switch (op)
{
case "+": {
v = tf1.getText();
if (v.equals("")) v = "0";
long i = Long.parseLong(v1)+Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}break;
case "-": {
v = tf1.getText(); if(v.equals(""))
v = "0";
long i = Long.parseLong(v1) - Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}break;
case "*": {
v = tf1.getText();
if (v.equals(""))
v = "0";
long i = Long.parseLong(v1) * Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
}break;

case "/": {
Aurora’s Technological & Research Institute 18
Department of IT Lab Manual

try {
v = tf1.getText(); if(v.equals("")) v = "0";
long i = Long.parseLong(v1) / Long.parseLong(v);
tf1.setText(String.valueOf(i));
v="";
} catch (Exception ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}break;

case "%": {
try {
v = tf1.getText(); if(v.equals(""))
v = "0";
long i = Long.parseLong(v1) % Long.parseLong(v);
tf1.setText(String.valueOf(i)); v="";
} catch (Exception ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}}
break;}}break;}}}

public class Calc


{
public static void main(String[] args) { A a = new A();
}
}

EXPECTED OUTPUT:

Aurora’s Technological & Research Institute 19


Department of IT Lab Manual

EXPERIMENT-3(A)

OBJECTIVE:
To develop an Applet in java that displays a Simple Message

PROGRAM LOGIC:
1. Start the program
2. Create a class with the name „Sms‟ extends Applet.
3. Declare the Font class object.
4. Set the font.
5. Call the setFont method and drawString method g.setFont(font); g.drawString(“String",
50, 50);
6.Create the HTML file for applet tag.

PROCEDURE:
To execute a java program we require setting a class path:
1.C:\set path= C:\Program Files\Java\ JDK1.7\bin;.;
2.C:\javac HelloJava.java
3.C:\appletviewer Sms.html

SOURCE CODE:
importjava.applet.Applet;
import java.awt.*;
public class HelloJava extends Applet
{
public void init()
{}
public void paint(Graphics g)
{
g.setColor(Color.blue);
Font font = new Font("verdana", Font.BOLD, 15); g.setFont(font);
g.drawString("Hello Java ", 50, 50);
}
}

Aurora’s Technological & Research Institute 20


Department of IT Lab Manual

Expected Output:

Aurora’s Technological & Research Institute 21


Department of IT Lab Manual

EXPERIMENT-3(B)

OBJECTIVE:
To 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 button named “Compute” is clicked

PROGRAM LOGIC:
 Start the program
 Create a class with the name “Fact‟ extends Applet which implements ActionListener.
 Declare the Label,TextField, Button variables.
 Call init method
 Call the setLayout method, setLayout(g);
 Create the HTML file for applet tag.

PROCEDURE:
1.C:\javac Fact.java
2.C:\appletviewer Fact.html

SOURCE CODE:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class Fact extends Applet implements ActionListener
{
Label l1, l2, l3;
TextField tf1, tf2;
Button b1;
public void init()
{
setSize(400, 200);
FlowLayout g = new FlowLayout();
setLayout(g);
l1 = new Label("Enter Value");
l1.setForeground(Color.BLUE);
add(l1);
tf1 = new TextField(5);
tf1.setText("0");

Aurora’s Technological & Research Institute 22


Department of IT Lab Manual

add(tf1);
b1 = new Button("Compute");
b1.addActionListener(this);
add(b1);
l3 = new Label();
add(l3);
l2 = new Label("factorial: ");
l2.setForeground(Color.BLUE);
add(l2);
tf2 = new TextField(5);
add(tf2);
}
public void actionPerformed(ActionEventae)
{
long n = Integer.parseInt(tf1.getText());
long f = 1;
while (n != 0)
{ f = f * n;
n--;
} tf2.setText(String.valueOf(f));
}
}
Expected Output:

Aurora’s Technological & Research Institute 23


Department of IT Lab Manual

EXPERIMENT-4

OBJECTIVE:
To creates User Interface to perform Integer Divisions. The user enters two numbers in text
fields, Num1 and Num2.The division of Num1 and Num2 is displayed in the result field when
the divide button clicked. If Num1 or Num2 were not integer, the program would throw a
NumberFormatException, If Num2 is Zero, and the program would throw an Arithmetic
Exception. Display the Exception in message box.

PROGRAM LOGIC:

 Start the program


 Create a class with the name “A extends JFrame‟.
 Declare the JLabel,JTextField,JButton variables.
 Declare the default constructor of the class.
 5.Addbuttons,TextField and labels to the Flow Layout.
 6.CallActionPerformed method.

PROCEDURE:

1.C:\javac JavaApplication9.java
2. C:\java JavaApplication9

SOURCE CODE:

importjava.awt.*;
import java.awt.event.*;
import javax.swing.*;
importjavax.swing.event.*;
class A1 extends JFrame implements ActionListener
{
JLabel l1, l2, l3;
JTextField tf1, tf2, tf3;
JButton b1;
A1()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Aurora’s Technological & Research Institute 24


Department of IT Lab Manual

setLayout(new FlowLayout());
l1 = new JLabel("Welcome");
setSize(800, 400);
l1 = new JLabel("Enter Number1");
add(l1);
tf1 = new JTextField(10);
add(tf1);
l2 = new JLabel("Enter Number2");
add(l2);
tf2 = new JTextField(10);
add(tf2);
l3 = new JLabel("Result");
add(l3);

tf3 = new JTextField(10);


add(tf3);
b1 = new JButton("Divide");
add(b1);
b1.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEventae)
{
try
{
int a = Integer.parseInt(tf1.getText());
int b = Integer.parseInt(tf2.getText());
if(b==0)
throw new ArithmeticException(" Divide by Zero Error");
float c = (float) a / b;
tf3.setText(String.valueOf(c));
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
catch (ArithmeticException ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
Aurora’s Technological & Research Institute 25
Department of IT Lab Manual

}
}
}
public class JavaApplication9
{
public static void main(String[] args)
{
A1 a = new A1();
}
}

EXPECTED OUTPUT:

Aurora’s Technological & Research Institute 26


Department of IT Lab Manual

Experiment: 5

OBJECTIVE:
Write Java Program that implements a multithread application that has three threads. First
thread generates Random integer for every second and if the value is even, second thread
computes the square of number and prints. If the value is odd, the third thread will print the
value of cube of number.

PROCEDURE:

1.C:\javac JavaApplication5.java
2. C:\java JavaApplication5

SOURCE CODE

import java.util.*;

class even implements Runnable


{
public int x;
public even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("New Thread "+ x +" is EVEN and Square of " + x + " is: " + x * x);
}
}
class odd implements Runnable
{
public int x;
public odd(int x)
{
this.x = x;
}
public void run()
{

Aurora’s Technological & Research Institute 27


Department of IT Lab Manual

System.out.println("New Thread "+ x +" is ODD and Cube of " + x + " is: " + x * x * x);
}
}
class A extends Thread
{
public void run()
{
Intnum = 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 JavaProgram5
{
public static void main(String[] args)
{
A a = new A();
a.start();
}
Aurora’s Technological & Research Institute 28
Department of IT Lab Manual

EXPECTED OUTPUT:

Aurora’s Technological & Research Institute 29


Department of IT Lab Manual

EXPERIMENT-6

OBJECTIVE
WriteaJavaprogramforthefollowing:

Createadoublylinkedlistofelements,
Deletea given elementfromtheabovelist,
Display thecontents of the list after deletion.

SOURCE CODE:

import java.io.*;
importjava.util.Scanner;

classlinkedlist {
int data;
linkedlistprev;
linkedlist next;

linkedlist(int value) {
this.data = value;
}

void display() {
System.out.println(data);
}
}
class linked {
publiclinkedlistfstnode, lastnode;

linked() {
fstnode = null;
lastnode = null;
}

/* Insert node at the beginning or create linked list */


voidinsert_front(int value) {
linkedlist node = new linkedlist(value);
if(fstnode == null) {
node.prev = node.next = null;
fstnode = lastnode = node;
System.out.println("Lined list created successfully!");

Aurora’s Technological & Research Institute 30


Department of IT Lab Manual

}
else {
node.prev = null;
node.next = fstnode;
fstnode.prev = node;
fstnode = node;
System.out.println("Node Inserted at the front of the Linked list!");
}
}

/* Insert node at the end or create linked list */


voidinsert_end(int value) {
linkedlist node = new linkedlist(value);
if(fstnode == null) {
node.prev = node.next = null;
fstnode = lastnode = node;
System.out.println("Lined list created successfully!");
}
else {
node.next = null;
node.prev = lastnode;
lastnode.next = node;
lastnode = node;
System.out.println("Node Inserted at the end of the Linked list!");
}
}
/* Delete node from linked list */
void delete() {
int count = 0, number, i;
linkedlist node, node1, node2;
Scanner input = new Scanner(System.in);

for(node = fstnode; node != null; node = node.next)


count++;
display();
node = node1 = node2 = fstnode;
System.out.println(count+" nodes available here!");
System.out.println("Enter the node number which you want to delete from
ascending order list:");
number = Integer.parseInt(input.nextLine());
if(number != 1) {
if(number < count && number > 0) {
for(i = 2; i <= number; i++)
node = node.next;

Aurora’s Technological & Research Institute 31


Department of IT Lab Manual

for(i = 2; i <= number-1; i++)


node1 = node1.next;
for(i = 2; i <= number+1; i++)
node2 = node2.next;
node2.prev = node1;
node1.next = node2;
node.prev = null;
node.next = null;
node = null;
}
else if(number == count) {
node = lastnode;
lastnode = node.prev;
lastnode.next = null;
node = null;
}
else
System.out.println("Invalid node number!\n");
}
else {
node = fstnode;
fstnode = node.next;
fstnode.prev = null;
node = null;
}

System.out.println("Node has been deleted successfully!\n");


}

/* Display linked list */


void display() {
linkedlist node = fstnode;
System.out.println("List of node in Ascending order!");
while(node != null) {
node.display();
node = node.next;
}

node = lastnode;
System.out.println("List of node in Descending order!");
while(node != null) {
node.display();
node = node.prev;
}

Aurora’s Technological & Research Institute 32


Department of IT Lab Manual

}
}
classdoublylinkedlist {
public static void main(String args[ ]) {
linked list = new linked();
Scanner input = new Scanner(System.in);
int op = 0;
while(op != 5) {
System.out.println("1. Insert at front 2. Insert at back 3. Delete 4. Display 5. Exit");
System.out.println("Enter your choice:");
op = Integer.parseInt(input.nextLine());
switch(op) {
case 1:
System.out.println("Enter the positive value for Linked list:");
list.insert_front(Integer.parseInt(input.nextLine()));
break;
case 2:
System.out.println("Enter the positive value for Linked list:");
list.insert_end(Integer.parseInt(input.nextLine()));
break;
case 3:
list.delete();
break;
case 4:
list.display();
break;
case 5:
System.out.println("Bye Bye!");
System.exit(0);
break;
default:
System.out.println("Invalid choice!");

}
}
}
}

EXPECTED OUTPUT:

1. Insert at front 2. Insert at back 3. Delete 4. Display 5. Exit

Enter your choice:

Aurora’s Technological & Research Institute 33


Department of IT Lab Manual

Enter the positive value for Linked list:

Linked list created successfully!

1. Insert at front 2. Insert at back 3. Delete 4. Display 5. Exit

Enter your choice:

Enter the positive value for Linked list:

Node inserted successfully!

1. Insert at front 2. Insert at back 3. Delete 4. Display 5. Exit

Enter your choice:

1
Enter the positive value for Linked list:
6
Node inserted successfully!
1. Insert at front 2. Insert at back 3. Delete 4. Display 5. Exit

Enter your choice:


2

Enter the positive value for Linked list:


7

Node inserted successfully!

1. Insert at front 2. Insert at back 3. Delete 4. Display 5. Exit

Enter your choice: 2

Enter the positive value for Linked list: 8

Aurora’s Technological & Research Institute 34


Department of IT Lab Manual

1. Insert at front 2. Insert at back 3. Delete 4. Display 5. Exit

Enter your choice: 4


List of node in Ascending order!

6
5
4
7
8

List of node in Descending order!


8
7
4
5
6

1. Insert at front 2. Insert at back 3. Delete 4. Display 5. Exit

Enter your choice:

List of node in Ascending order!

6
5
4
7
8

List of node in Descending order!

8
7
4
5
6
5
nodes available here!
Enter the node number which you want to delete from ascending order list:

Aurora’s Technological & Research Institute 35


Department of IT Lab Manual

Node has been deleted successfully!

1. Insert at front 2. Insert at back 3. Delete 4. Display 5. Exit

Enter your choice:

Bye Bye!

Aurora’s Technological & Research Institute 36


Department of IT Lab Manual

EXPERIMENT-7

OBJECTIVE
To simulate a Traffic Light. The program lets the use select one of three lights :red, yellow or
Green with radio buttons. On selecting radio button, an appropriate message with “stop” or
“Ready” or “GO” should appear above the button in selected color. Intially ,there is no
message Shown.

PROGRAM LOGIC:
1. Start the program
2. Create a class with the name A implements ItemListener.
3. Create the ButtonGroup ,JRadiobuttons,JPanel.
4. Add to the JFrame
5. Register the components to the Jframe.
6. Close the Jframe.

PROCEDURE:
To execute a java program we require setting a class path:
1.C:\set path= C:\Program Files\Java\ JDK1.7\bin;.;
2.C:\javac TLights.java
3.C:\java TLights

SOURCE CODE:

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

class A extends JFrame implements ItemListener


{
public JLabel l1, l2;
publicJRadioButton r1, r2, r3;
public ButtonGroupbg;
public JPanel p, p1;
public A()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2, 1));
setSize(800, 400);
p = new JPanel(new FlowLayout());
p1 = new JPanel(new FlowLayout());
l1 = new JLabel();

Aurora’s Technological & Research Institute 37


Department of IT Lab Manual

Font f = new Font("Verdana", Font.BOLD, 60);


l1.setFont(f);
add(l1);
p.add(l1);
add(p);
l2 = new JLabel("Select Lights"); p1.add(l2);
JRadioButton r1 = new JRadioButton("Red Light");
r1.setBackground(Color.red);
p1.add(r1); r1.addItemListener(this);
JRadioButton r2 = new JRadioButton("Yellow Light");
r2.setBackground(Color.YELLOW);
p1.add(r2); r2.addItemListener(this);

JRadioButton r3 = new JRadioButton("Green Light");


r3.setBackground(Color.GREEN);
p1.add(r3); r3.addItemListener(this);
add(p1);
bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
bg.add(r3);
setVisible(true);
}

public void itemStateChanged(ItemEventi)


{
JRadioButtonjb = (JRadioButton) i.getSource();
switch (jb.getText())
{
case "Red Light": {

l1.setText("STOP");
l1.setForeground(Color.red);
} break;
case "Yellow Light": { l1.setText("Ready");
l1.setForeground(Color.YELLOW);} break;
case "Green Light": { l1.setText("GO");
l1.setForeground(Color.GREEN);
} break;
}
}
}

public class TLights { public static void main(String[] args) {

Aurora’s Technological & Research Institute 38


Department of IT Lab Manual

A a = new A();
}}

EXPECTED OUTPUT:

Aurora’s Technological & Research Institute 39


Department of IT Lab Manual

EXPERIMENT-8

OBJECTIVE:
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 subclass that
each one of the classes extends the Class Shape .Each one of the classes contains only the
method printArea() that prints the area of Shape.

PROGRAM LOGIC:
1. Start the program
2. Create a class with the name Shape.
3. Create the Rectangle,Triangle,Circle extends Shape.
4. Create the objects to the individual classes.
5. Call the PrintArea() on individual object.

PROCEDURE:
To execute a java program we require setting a class path: 1.C:\set path= C:\Program
Files\Java\ JDK1.7\bin;.; 2.C:\javac Abstex.java
3.C:\java Abstex

SOURCE CODE:

import java.util.*;
abstract class shape
{
public int x,y;
public abstract void printArea();
}
class Rectangle1 extends shape
{
public void printArea()
{
float area;
area= x * y;
System.out.println("Area of Rectangle is " +area);
}
}
class Triangle extends shape
Aurora’s Technological & Research Institute 40
Department of IT Lab Manual

{
public void printArea()
{
float area;
area= (x * y) / 2;
System.out.println("Area of Triangle is " + area);
}
}
class Circle extends shape
{
public void printArea()
{
float area;
area=(22 * x * x) / 7;
System.out.println("Area of Circle is " + area);
}
}
public class Shapes
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter values : ");


int x1=sc.nextInt();
int y1=sc.nextInt();

Rectangle1 r = new Rectangle1();


r.x = x1; r.y = y1;
r.printArea();

Triangle t = new Triangle();


t.x = x1; t.y = y1;
t.printArea();

Circle c = new Circle();


c.x = x1;
c.printArea();
}
Aurora’s Technological & Research Institute 41
Department of IT Lab Manual

EXPECTED OUTPUT:

Aurora’s Technological & Research Institute 42


Department of IT Lab Manual

EXPERIMENT-9

OBJECTIVE:
To display a table using Label in Grid Layout.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 corresponding
rows in table. The elements are separated by commas.

PROGRAM LOGIC:
1. Start the program
2. Create a class with the name A implements ItemListener.
3.Create the FileInputStream object.
4.Create the Scanner object delimited by comma.
5.Close the Jframe.

SOURCE CODE:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class Table1 extends JFrame
{
int i=0;
int j=0,k=0;
Object data[][]=new Object[5][4];
Object list[][]=new Object[5][4];
JButton save;
JTable table1;
FileInputStream fis;
DataInputStream dis;
public Table1()
{
String d= " ";
Container con=getContentPane();

Aurora’s Technological & Research Institute 43


Department of IT Lab Manual

con.setLayout(new BorderLayout());
final String[] colHeads={"Name","Roll Number","Department","Percentage"};
try
{
String s=JOptionPane.showInputDialog("Enter the File name present in the current directory");
FileInputStream fis=new FileInputStream(s);
DataInputStream dis = new DataInputStream(fis);
while ((d=dis.readLine())!=null)
{
StringTokenizer st1=new StringTokenizer(d,",");
while (st1.hasMoreTokens())
{
for (j=0;j<4;j++)
{
data[i][j]=st1.nextToken();
System.out.println(data[i][j]);
}
i++;
}
System.out.println ("______________");
}
} catch (Exception e)
{
System.out.println ("Exception raised" +e.toString());
}
table1=new JTable(data,colHeads);
int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane scroll=new JScrollPane(table1,v,h);
con.add(scroll,BorderLayout.CENTER);
}
public static void main(String args[])
{

Aurora’s Technological & Research Institute 44


Department of IT Lab Manual

Table1 t=new Table1();


t.setBackground(Color.green);
t.setTitle("Display Data");
t.setSize(500,300);
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}}
EXPECTED OUTPUT:
Abc.txt:-
a,123,der,23
b,456,frg,45

Aurora’s Technological & Research Institute 45


Department of IT Lab Manual

Aurora’s Technological & Research Institute 46


Department of IT Lab Manual

EXPERIMENT-10

OBJECTIVE:

Write a Java Program that handles all mouse events and show event name at the center of the
window when the mouse event is fired. (Use Adapter Classes)

importjavax.swing.*;
importjava.awt.*;
importjavax.swing.event.*;
importjava.awt.event.*;
class A extends JFrame implements MouseListener
{
JLabel l1;
public A()
{
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_ALIGNM
ENT);
l1.setAlignmentY(Component.CENTER_ALIGNM
ENT); 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)
{

Aurora’s Technological & Research Institute 47


Department of IT Lab Manual

l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
}
public class Mevents
{
public static void main(String[] args)
{
A a = new A();
}
}
EXPECTED OUTPUT:

Aurora’s Technological & Research Institute 48


Department of IT Lab Manual

EXPERIMENT-11

OBJECTIVE:
To load the names and phone numbers from the text file where data is organized as one line
per record and each field in record are separated by a tab(\t).It takes a name or phone number
as input and prints corresponding other value from hash table.(hint: use Hash Table)

PROGRAM LOGIC:
1. Start the program
2. Create a class with the name Hashtbl
3. Create FileInputStream, Scanner, Hashtable objects
4. Read the data from the hash table.
5. Display the data.

PROCEDURE:
To execute a java program we require setting a class path:
1.C:\set path= C:\Program Files\Java\ JDK1.7\bin;.;
2.C:\javac Hashtbl.java
3.C:\java Hashtbl

SOURCE CODE:
importjava.util.*;
import java.io.*;
public class Hashtbl
{
public static void main(String[] args)
{
try
{
FileInputStreamfs = new FileInputStream("D:\\ph.txt");
Scanner sc = new Scanner(fs).useDelimiter("\\s+");
Hashtable<String, String>ht = new Hashtable<String, String>(); String[] arrayList;
String a;
System.out.println("Welcome to Aurora’s Technological and Research Institute ");
System.out.println("HASH TABLE IS");
System.out.println("--------------------------");
System.out.println("KEY : VALUE");
while (sc.hasNext())
Aurora’s Technological & Research Institute 49
Department of IT Lab Manual

{
a = sc.nextLine();
arrayList = a.split("\\s+");
ht.put(arrayList[0], arrayList[1]);
System.out.println(arrayList[0] + ":" + arrayList[1]);
}
System.out.println("----MENU------");
System.out.println("----1.Search by Name------");
System.out.println("----2.Search by Mobile------");
System.out.println("----3.Exit------");
String opt = "";
String name, mobile;
Scanner s = new Scanner(System.in);
while (opt != "3")
{
System.out.println("Enter Your Option 1,2,3");
opt = s.next();
switch (opt)
{
case "1":
{
System.out.println("Enter Name"); name = s.next();
if (ht.containsKey(name))
{
System.out.println("Mobile is " + ht.get(name));
}
else { System.out.println("Not Found"); }}
break;
case "2":
{
System.out.println("Enter mobile"); mobile = s.next();
if (ht.containsValue(mobile))
{
for (Map.Entry e : ht.entrySet())
{
if (mobile.equals(e.getValue()))
{
System.out.println("Name is " + e.getKey());
}
Aurora’s Technological & Research Institute 50
Department of IT Lab Manual

}
}
else
{
System.out.println("Not Found");
}
}
break;
case "3":
{
System.out.println("Menu Successfully Exited"); } break; default:
System.out.println("Choose Option betwen 1 and Three"); break;
}
}
}
catch (Exception ex)
{ System.out.println(ex.getMessage()); }
}
}
EXPECTED OUTPUT:

Aurora’s Technological & Research Institute 51


Department of IT Lab Manual

EXPERIMENT-12

OBJECTIVE:
Write a Java program that correctly implements the producer – consumer problem using the
concept of interthread communication.

PROGRAM LOGIC:
1. Start the program
2. Create a class with the name Threadexample
3. Display the data.

PROCEDURE:
To execute a java program we require setting a class path:
1. C:\set path= C:\Program Files\Java\ JDK1.7\bin
2. C:\javacThreadexample.java
3. C:\java Threadexample

SOURCE CODE:

import java.util.LinkedList;
public class Threadexample
{
public static void 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()
{
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
Aurora’s Technological & Research Institute 52
Department of IT Lab Manual

}
}
});

// Create consumer thread


Thread t2 = new Thread(new Runnable()
{

public void run()


{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
});

// Start both threads


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

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

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


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

Aurora’s Technological & Research Institute 53


Department of IT Lab Manual

// Function called by producer thread


public void produce() throws InterruptedException
{
int value = 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++);
notify();
Thread.sleep(1000);
}
}
}

// Function called by consumer thread


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

//to retrive the ifrst job in the list


intval = list.removeFirst();
System.out.println("Consumer consumed-" + val);
// Wake up producer thread
notify();
Aurora’s Technological & Research Institute 54
Department of IT Lab Manual

// and sleep
Thread.sleep(1000);
}
}
}
}
}
EXPECTED OUTPUT:

Aurora’s Technological & Research Institute 55


Department of IT Lab Manual

EXPERIMENT-13

OBJECTIVE:
Writea Java program to list all the files in a directory including the files present in all its sub
directories.

SOURCE CODE:
import java.io.File;

public class Directory


{
static void RecursivePrint(File[] arr,int index,int level)
{
// terminate condition
if(index == arr.length)
return;

// tabs for internal levels


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

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

// for sub-directories
else if(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
public static void main(String[] args)
{
// Provide full path for directory(change accordingly)
String maindirpath = "G:\\CSI";

// File object

Aurora’s Technological & Research Institute 56


Department of IT Lab Manual

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("**********************************************");
System.out.println("Files from main directory : "+ maindir);
System.out.println("**********************************************");

// Calling recursive method


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

EXPECTED OUTPUT:

Aurora’s Technological & Research Institute 57


Department of IT Lab Manual

EXPERIMENT-14

OBJECTIVE:
Writea Java program that implements Quick sort algorithm for sorting alist of numbers in ascending
order.

SOURCE CODE:

importjava.util.Scanner;
public class QuickSort
{

Public staticvoid sort(int[] arr)


{
quickSort(arr, 0, arr.length - 1);
}
/** Quick sort function **/
public static void quickSort(intarr[], int low, int high)
{
int i = low, j = high;
int temp;
int pivot = arr[(low + high) / 2];

/** partition **/


while (i <= j)
{
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j)
{
/** swap **/
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;

i++;
j--;
}

Aurora’s Technological & Research Institute 58


Department of IT Lab Manual

/** recursively sort lower half **/


if (low < j)
quickSort(arr, low, j);
/** recursively sort upper half **/
if (i < high)
quickSort(arr, i, high);
}
/** Main method **/
publicstaticvoid main(String[] args)
{
Scanner scan = newScanner( System.in );
System.out.println("Quick Sort Test\n");
int n, i;
/** Accept number of elements **/
System.out.println("Enter number of integer elements");
n = scan.nextInt();
/** Create array of n elements **/
intarr[] = newint[ n ];
/** Accept elements **/
System.out.println("\nEnter "+ n +" integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
/** Call method sort **/
sort(arr);
/** Print sorted Array **/
System.out.println("\nElements after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}

EXPECTED OUPUT:
Enter number of integer elements
10
Enter 10 integer elements
877 567 3456 876 467 26 934 9876 1 4567
Elements after sorting
1 26 467 567 876 877 934 3456 4567 9876

Aurora’s Technological & Research Institute 59


Department of IT Lab Manual

EXPERIMENT-15

OBJECTIVE:
Write a Java program that implements Bubble sort algorithm for sorting in descending order
and also shows the number of interchanges occurred for the given set of integers.

PROGRAM LOGIC:
1. Start the program
2. Create a class with the name Threadexample
3. Display the data.

PROCEDURE:

To execute a java program we require setting a class path:


1.C:\set path= C:\Program Files\Java\ JDK1.7\bin;.; 2.C:\javacThreadexample.java
3.C:\java Threadexample

SOURCE CODE:
import java.util.Scanner;

class BubbleSort
{
public static void main(String []args)
{
int num, i, j, temp,count=0;
Scanner input = new Scanner(System.in);

System.out.println("Enter the number of integers to sort:");


num = input.nextInt();
int array[] = new int[num];

System.out.println("Enter " + num + " integers: ");


for (i = 0; i <num; i++)
array[i] = input.nextInt();

for (i = 0; i < ( num - 1 ); i++)


{
for (j = 0; j <num - i - 1; j++)
{

Aurora’s Technological & Research Institute 60


Department of IT Lab Manual

if (array[j] < array[j+1])


{
count++;
temp = array[j];
array[j] = array[j+1];
array[j+1] = te mp;
}
}
}

System.out.println("Sorted list of integers:");


for (i = 0; i <num; i++)
System.out.println(array[i]);
System.out.println(count);
}
}
EXPECTED OUTPUT:

Aurora’s Technological & Research Institute 61

You might also like