Java Programming Lab
Java Programming Lab
Java Programming
Computer Science & Engineering | Information Technology
(II- B. Tech. – II– Semester)
1
1. Syllabus
CS408PC: JAVA PROGRAMMING LAB
2
PROGRAM OUTCOMES (PO’s)
PO2 An ability to analyze a problem, and identify and formulate the computing
requirements appropriate to its solution.
PO3 An ability to design, implement, and evaluate a computer-based system, process, component,
or program to meet desired needs with appropriate consideration for public health and safety,
cultural, societal and environmental considerations.
PO4 An ability to design and conduct experiments, as well as to analyze and interpret data.
PO5 An ability to use current techniques, skills, and modern tools necessary for computing
practice.
PO6 An ability to analyze the local and global impact of computing on individuals, organizations,
and society.
PO8 An understanding of professional, ethical, legal, security and social issues and
responsibilities.
PO9 An ability to function effectively individually and on teams, including diverse and
multidisciplinary, to accomplish a common goal.
PO11 An understanding of engineering and management principles and apply these to one’s own
work, as a member and leader in a team, to manage projects.
PO12 Recognition of the need for and an ability to engage in continuing professional development.
3
[Link]
3. Lesson/Course Plan
No. of
Week Text Mode of
Name of the Program Hours
No. Books Assessment
required
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
1 1 1 Viva & Execution
code refactoring like renaming variables, methods,
and classes. Try debug step by step with a small
program of about 10 to 15 lines which contains at least
one if else condition and a for loop.
Write a Java program that works as a simple calculator.
Use a grid layout to arrange buttons for the
2 digits and for the +, -,*, % operations. Add a text field to 1 T1 Viva & Execution
display the result. Handle any possible
exceptions like divided by zero.
a) Develop an applet in Java that displays a
simple message.
b) Develop an applet in Java that receives an integer
3 1 T1 Viva & Execution
in one text field, and computes its factorial Value
and returns it in another text field, when the button
named “Compute” is clicked.
Write a Java program that creates a user interface
to 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
4 Num1 or Num2 were not an integer, the program 1 T1 Viva & Execution
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 has three threads. First thread
generates random integer every 1 second and if the value
5 is even, second thread computes the 1 T1 Viva & Execution
square 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:
Create a doubly linked list of elements.
6 1 T1 Viva & Execution
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 the user select one of three
lights: red, yellow, or green with radio buttons. On
7 selecting a button, an appropriate message with 1 T1 Viva & Execution
“Stop” 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
8 classes named Rectangle, Triangle, and Circle 1 T1 Viva & Execution
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
4
[Link]
shape.
Suppose that a table named [Link] is stored in a text
file. The first line in the file is the header,
and the remaining lines correspond to rows in the
9 table. The elements are separated by commas. 1 T1 Viva &
Write a java program to display the table using Labels in Execution
Grid Layout.
Write a Java program that handles all mouse events and
shows the event name at the center of the
10 window when a mouse event is fired (Use Adapter 1 T1 Viva &
classes). Execution
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
11 record are separated by a tab (\t). It takes a 1 T1 Viva &
name or phone number as input and prints the Execution
corresponding other value from the hash table (hint:
use hash tables).
Write a Java program that correctly implements
12 the producer – consumer problem using the 1 T1 Viva &
concept of interthread communication. Execution
Write a Java program to list all the files in a directory
13 including the files present in all its 1 T1 Viva &
subdirectories. Execution
Write a Java program that implements Quick sort
14 algorithm for sorting a list of names in ascending 1 T1 Viva &
Order Execution
Write a Java program that implements Bubble sort
algorithm for sorting in descending order and
15 also shows the number of interchanges occurred for
1 T1 Viva &
the given set of integers. Execution
16 LEAD Experiments' 1 T1 Viva &
Execution
Total no of HOURS required to complete
16
syllabus
5
PROGRAMS
Week 1.
Aim: Use Eclipse or Net bean platform and acquaint with the various menus. Create a test project, add a test class,
and run it. See how you can use auto suggestions, auto fill. Try code formatter and code refactoring like renaming
variables, methods, and classes. Try debug step by step with a small program of about 10 to 15 lines which contains at
least one if else condition and a for loop.
Solution:
6
Select the sultable version based on your OS.
7
Double click on the Eclipse Application.
8
Click on Eclipse IDE for Java Developers.
9
Click on Install button.
10
Then the Eclipse installation begins.
Click on Accept
11
Click on Select All and Accept Selected.
12
[Link]
13
CREATING PROJECT AND CLASSES IN ECLIPSE IDE
Browse the Workspace for storing the java project and click on Launch.
14
Now, create the class in src directory from Package Explorer window.
15
Type the class name and click on Finish.
16
Click on Play button to run or execute the java code.
17
Week 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.
Source Code:
import [Link].*;
import [Link].*;
import [Link].*;
/*
* <applet code="Calculator" width=500 height=500></applet>
* */
18
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
String str=[Link]();
char ch=[Link](0);
if ( [Link](ch))
[Link]([Link]()+str);
else
if([Link]("+"))
{
v1=[Link]([Link]());
OP='+';
[Link]("");
}
else if([Link]("-"))
{
v1=[Link]([Link]()); OP='-';
[Link]("");
}
else if([Link]("*"))
{
v1=[Link]([Link]());
OP='*';
[Link]("");
}
else if([Link]("/"))
{
v1=[Link]([Link]());
OP='/';
[Link]("");
}
else if([Link]("%")){
v1=[Link]([Link]());
OP='%';
[Link]("");
}
if([Link]("=")){
v2=[Link]([Link]());
if(OP=='+')
result=v1+v2;
else if(OP=='-')
result=v1-v2;
else if(OP=='*')
result=v1*v2;
else if(OP=='/')
result=v1/v2;
else if(OP=='%')
result=v1%v2;
[Link](""+result);
}
if([Link]("Clear"))
{
[Link]("");
}
}
}
19
Output
20
Week 3:
// Import the packages to access the classes and methods in awt and applet classes.
import [Link].*;
import [Link].*;
/* <applet code="AppletExample" width=200 height=300></applet>*/
public class AppletExample extends Applet {
public void paint(Graphics g) {
[Link]("Hello World!",20,20);
}
}
Output:
import [Link].*;
import [Link].*;
import [Link];
/*<applet code="[Link]" height=300 width=300></applet>*/
public class Factorial extends Applet implements ActionListener {
Label l1,l2; TextField t1,t2; Button b1;
public void init(){
l1=new Label("Enter any integer value: "); add(l1);
t1=new TextField(5); add(t1);
b1=new Button("Calculate"); add(b1); [Link](this);
l2=new Label("Factorial of given integer number is "); add(l2);
t2=new TextField(10); add(t2);
}
public void actionPerformed(ActionEvent e){
if([Link]()==b1){
int fact=fact([Link]([Link]()));
[Link]([Link](fact));
}
}
21
int fact(int f) {
if(f==0) return 1;
else return f*fact(f-1);
}
}
Output:
22
Week 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.
Source code:
import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="DivisionExample"width=230 height=250></applet>*/
public class DivisionExample extends Applet implements ActionListener {
String msg; TextField num1, num2, res; Label l1, l2, l3; Button div;
public void init() {
l1 = new Label("Dividend"); l2 = new Label("Divisor"); l3 = new Label("Result");
num1 = new TextField(10); num2 = new TextField(10); res = new TextField(10);
div = new Button("Click");
[Link](this); add(l1); add(num1); add(l2); add(num2); add(l3);
add(res); add(div);
}
public void actionPerformed(ActionEvent ae) {
String arg = [Link](); int num1 = 0, num2 = 0;
if ([Link]("Click")) {
try {
num1 = [Link]([Link]());
num2 = [Link]([Link]());
int num3 = num1 / num2; [Link]([Link](num3));
msg = "Operation Succesfull!!!"; repaint();
} catch (NumberFormatException ex) { [Link](""); msg =
"NumberFormatException"; repaint(); }
catch (ArithmeticException e) { [Link](""); msg = "Can't divide by
Zero"; repaint(); }
}
}
public void paint(Graphics g) { [Link](msg, 30, 70); }
}
Output:
[Link]
23
Week 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.
Source code:
import [Link];
class RandomNumberThread extends Thread {
public void run() {
Random random = new Random();
for (int i = 0; i < 10; i++) {
int randomInteger = [Link](100);
[Link]("Random Integer generated : " + randomInteger);
if((randomInteger%2) == 0) {
SquareThread sThread = new SquareThread(randomInteger);
[Link]();
} else {
CubeThread cThread = new CubeThread(randomInteger);
[Link]();
}
try {
[Link](1000);
} catch (InterruptedException ex) { [Link](ex); }
}
}
}
class SquareThread extends Thread {
int number;
SquareThread(int randomNumber) { number = randomNumber; }
public void run() {
[Link]("Square of " + number + " = " + (number * number));
}
}
class CubeThread extends Thread {
int number;
CubeThread(int randomNumber) { number = randomNumber; }
public void run() {
[Link]("Cube of " + number + " = " + number * number * number);
}
}
public class MultiThreadingTest {
public static void main(String args[]) {
RandomNumberThread rnThread = new RandomNumberThread();
[Link]();
}
}
Output:
24
25
Week6:
Source code:
Output:
26
Week 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.
Source code:
import [Link];
import [Link].*;
import [Link].*;
/*
<applet code = "TrafficLightsExample" width = 1000 height = 500>
</applet>
*/
public class TrafficLightsExample extends Applet implements ItemListener {
CheckboxGroup grp = new CheckboxGroup();
Checkbox redLight, yellowLight, greenLight; Label msg;
public void init(){
redLight = new Checkbox("Red", grp, false);
yellowLight = new Checkbox("Yellow", grp, false);
greenLight = new Checkbox("Green", grp, false);
msg = new Label("");
[Link](this); [Link](this);
[Link](this);
add(redLight); add(yellowLight); add(greenLight); add(msg);
[Link](new Font("Serif", [Link], 20));
}
public void itemStateChanged(ItemEvent ie) {
if([Link]()) { [Link]([Link]); [Link]("STOP"); }
else if([Link]()) { [Link]([Link]); [Link]("READY"); }
else if([Link]()) { [Link]([Link]); [Link]("GO"); }
}
}
Output:
27
Week 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.
Source code:
import [Link].*;
abstract class Shape {
int length, breadth, radius;
Scanner input = new Scanner([Link]);
abstract void printArea();
}
class Rectangle extends Shape {
void printArea() {
[Link]("Enter length and breadth: ");
length = [Link](); breadth = [Link]();
[Link]("Area of Rectangle: " + length * breadth);
}
}
class Triangle extends Shape {
void printArea() {
[Link]("Enter Base And Height: ");
length = [Link](); breadth = [Link]();
[Link]("Area of Triangle: " + (length * breadth)/2);
}
}
class Circle extends Shape {
void printArea() {
[Link]("Enter Radius: ");
radius = [Link]();
[Link]("Area of Circle: " + 3.14f * radius * radius);
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Rectangle rec = new Rectangle(); [Link]();
Triangle tri = new Triangle(); [Link]();
Circle cir = new Circle(); [Link]();
}
}
Output:
28
Week 9:
Suppose that a table named [Link] 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.
Source code:
import [Link].*;
abstract class Shape {
int length, breadth, radius;
Scanner input = new Scanner([Link]);
abstract void printArea();
}
class Rectangle extends Shape {
void printArea() {
[Link]("Enter length and breadth: ");
length = [Link](); breadth = [Link]();
[Link]("Area of Rectangle: " + length * breadth);
}
}
class Triangle extends Shape {
void printArea() {
[Link]("Enter Base And Height: ");
length = [Link](); breadth = [Link]();
[Link]("Area of Triangle: " + (length * breadth)/2);
}
}
class Circle extends Shape {
void printArea() {
[Link]("Enter Radius: ");
radius = [Link]();
[Link]("Area of Circle: " + 3.14f * radius * radius);
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Rectangle rec = new Rectangle(); [Link]();
Triangle tri = new Triangle(); [Link]();
Circle cir = new Circle(); [Link]();
}
}
Output:
29
30
Week 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).
Source code:
import [Link].*;
import [Link].*;
import [Link].*;
/*<applet code="MouseDemo" width=300 height=300></applet>*/
public class MouseDemo extends Applet implements MouseListener,
MouseMotionListener {
int mx = 0; int my = 0; String msg = "";
public void init() { addMouseListener(this); addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me) { mx = 20; my = 40; msg = "Mouse
Clicked"; repaint(); }
public void mousePressed(MouseEvent me) { mx = 30; my = 60; msg = "Mouse
Pressed"; repaint(); }
public void mouseReleased(MouseEvent me) { mx = 30; my = 60; msg = "Mouse
Released"; repaint(); }
public void mouseEntered(MouseEvent me) { mx = 40; my = 80; msg = "Mouse
Entered"; repaint(); }
public void mouseExited(MouseEvent me) { mx = 40; my = 80; msg = "Mouse
Exited"; repaint(); }
public void mouseDragged(MouseEvent me) { mx = [Link](); my = [Link]();
showStatus("Mouse dragged" + mx + " " + my); repaint(); }
public void mouseMoved(MouseEvent me) { mx = [Link](); my = [Link]();
showStatus("Mouse at" + mx + " " + my); repaint(); }
public void paint(Graphics g) { [Link]("Handling Mouse Events", 30,
20); [Link](msg, 60, 40); }
}
Output:
31
Week 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)
Source code:
import [Link].*;
import [Link].*;
public class HashTab {
public static void main(String[] args) {
HashTab prog11 = new HashTab();
Hashtable<String, String> hashData = [Link]("[Link]");
[Link]("File data into Hashtable:\n" + hashData);
[Link](hashData, "raja");
[Link](hashData, "123");
}
private void printTheData(Hashtable<String, String> hashData, String input) {
String output = null;
if (hashData != null) {
Set<String> keys = [Link]();
if ([Link](input)) { output = [Link](input); }
else {
for (String key : keys) {
String value = [Link](key);
if ([Link](input)) { output = key; break; }
}
}
}
[Link]("Input: " + input);
if (output != null) [Link]("Data found: " + output);
else [Link]("Data not found");
}
private Hashtable<String, String> readFromFile(String fileName) {
Hashtable<String, String> hashData = new Hashtable<String, String>();
try {
File f = new File(fileName); BufferedReader br = new BufferedReader(new
FileReader(f));
String line = null;
while ((line = [Link]()) != null) {
String[] details = [Link](" "); [Link](details[0], details[1]);
}
} catch (Exception e) { [Link](); }
return hashData;
}
}
Output:
32
33
Week – 12
Write a Java program that correctly implements the producer – consumer problem using the concept of
interthread communication.
Source Code:
class ItemQueue {
int item; boolean valueSet = false;
synchronized int getItem() {
while (!valueSet) try { wait(); } catch (InterruptedException e) {}
[Link]("Consumed:" + item); valueSet = false; notify(); return item;
}
synchronized void putItem(int item) {
while (valueSet) try { wait(); } catch (InterruptedException e) {}
[Link] = item; valueSet = true; [Link]("Produced: " + item); notify();
}
}
class Producer implements Runnable{
ItemQueue itemQueue;
Producer(ItemQueue itemQueue){ [Link] = itemQueue; new Thread(this,
"Producer").start(); }
public void run() { int i = 0; while(true) { [Link](i++); } }
}
class Consumer implements Runnable{
ItemQueue itemQueue;
Consumer(ItemQueue itemQueue){ [Link] = itemQueue; new Thread(this,
"Consumer").start(); }
public void run() { while(true) { [Link](); } }
}
public class ProducerConsumer{
public static void main(String args[]) { ItemQueue itemQueue = new ItemQueue(); new
Producer(itemQueue); new Consumer(itemQueue); }
}
Output:
34
35
Week – 13
Write a Java program to list all the files in a directory including the files present in all its subdirectories.
Source Code:
import [Link];
import [Link].*;
37
Week 14
Write a Java program that implements Quick sort algorithm for sorting a list of names in ascending
Order.
Source Code:
public class QuickSortOnStrings {
String names[]; int length;
public static void main(String[] args) {
QuickSortOnStrings obj = new QuickSortOnStrings();
String stringsList[] = {"raja", "gouthu", "rani", "gouthami", "honey"};
[Link](stringsList);
for (String i : stringsList) { [Link](i + " "); }
}
void sort(String array[]) {
if (array == null || [Link] == 0) return;
[Link] = array; [Link] = [Link]; quickSort(0, length - 1);
}
void quickSort(int lowerIndex, int higherIndex) {
int i = lowerIndex; int j = higherIndex;
String pivot = [Link][lowerIndex + (higherIndex - lowerIndex) / 2];
while (i <= j) {
while ([Link][i].compareToIgnoreCase(pivot) < 0) { i++; }
while ([Link][j].compareToIgnoreCase(pivot) > 0) { j--; }
if (i <= j) { exchangeNames(i, j); i++; j--; }
}
if (lowerIndex < j) quickSort(lowerIndex, j);
if (i < higherIndex) quickSort(i, higherIndex);
}
void exchangeNames(int i, int j) { String temp = [Link][i]; [Link][i] =
[Link][j]; [Link][j] = temp; }
}
Output:
38
Week 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.
Source Code:
import [Link];
public class BubbleSort {
public static void main(String[] args) {
Scanner read = new Scanner([Link]); int size, count = 0;
[Link]("Enter the list size: "); size = [Link]();
int list[] = new int[size];
[Link]("Enter " + size + " integers: ");
for(int i = 0; i < size; i++) list[i] = [Link]();
int temp=0;
for(int i=0;i<size-1;i++) {
for(int j=0;j<size-i-1;j++) {
if(list[j]<list[j+1]) { temp=list[j]; list[j]=list[j+1];
list[j+1]=temp; count++; }
}
}
[Link]("Sorted list: ");
for(int x:list) { [Link](x + " "); }
[Link]("\nTotal number of Interchanges: " + count);
}
}
39
Output:
40