0% found this document useful (0 votes)
125 views41 pages

Java Lab Manual SDES

The document describes a Java program that implements a simple calculator application using a graphical user interface. The program uses a grid layout to arrange the buttons for numbers, operations (+ - * / %), and an equals button. It also includes a text field to display the result. The program handles exceptions like divide by zero. When the user presses a button, the corresponding number or operation is added to a string and displayed in the text field. When equals is pressed, the calculation is performed based on the stored operation and numbers, and the result is displayed.

Uploaded by

temp
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
125 views41 pages

Java Lab Manual SDES

The document describes a Java program that implements a simple calculator application using a graphical user interface. The program uses a grid layout to arrange the buttons for numbers, operations (+ - * / %), and an equals button. It also includes a text field to display the result. The program handles exceptions like divide by zero. When the user presses a button, the corresponding number or operation is added to a string and displayed in the text field. When equals is pressed, the calculation is performed based on the stored operation and numbers, and the result is displayed.

Uploaded by

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

SREE DATTHA

Institute of Engineering and Science

Department of Computer Science &Engineering

OBJECT ORIENTED PROGRAMMING


THROUGH JAVA LAB MANUAL
[Subject Code: CS308ES]
For the Academic year 2017-18
II B Tech II Semester
1
Course Objectives:
1. To write programs using abstract classes.
2. To write programs for solving real world problems using java collection frame work.
3. To write multithreaded programs.
4. To write GUI programs using swing controls in Java.
5. To introduce java compiler and eclipse platform.
6. To impart hands on experience with java programming.

Course Outcomes:
1. Able to write programs for solving real world problems using java collection framework.
2. Able to write programs using abstract classes.
3. Able to write multithreaded programs.
4. Able to write GUI programs using swing controls in Java.

2
List of Experiments

1. Use eclipse or Netbean platform and acquaint with the various menus, create a test
project, add a test class and run it see how you can use auto suggestions, auto fill. Try
code formatter and code refactoring like renaming variables, methods and classes. Try
debug step by step with a small program of about 10 to 15 lines which contains at least
one if else condition and a for loop.
2. Write a Java program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +, -,*, % operations. Add a text field to display the
result. Handle any possible exceptions like divide by zero.
3. a. Develop an applet that displays a simple message
b. Develop an Applet that receives an integer in one text field & compute its factorial
value & returns it in another text filed when the button “Compute” is clicked
4. Write a program that creates a user interface to perform integer divisions. The user enters
two numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is
displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were
not an integer, the program would throw a NumberFormatException. If Num2 were Zero,
the program would throw an Arithmetic Exception Display the exception in a message
dialog box
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 a 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 printArea(). Provide three classes named Rectangle,
Triangle and Circle such that each one of the classes extends the class Shape. Each one of
the classes contain only the method printArea( ) that prints the area of the given shape.

3
9. Suppose that a table named Table.txt is stored in a text file. The first line in the file header
and the remaining lines correspond to row in the table. The elements are separated by
commas. Write a Java program to display the table using labels in grid layout.
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 Strings 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.

4
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.
Aim: Implement sample java program using eclipse or Netbeans & use its code formatter
code refactoring (renaming variable) & debug step by step.

Program:
import java.util.*;
public class Testp
{
public static void main(String[] args) {
System.out.println("Welcome to Siddhartha Engineering College");
Scanner sc = new Scanner(System.in);
System.out.println("Enter valid Number");
int n = sc.nextInt();
int c = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
c++;
}
}
if (c == 2)
{
System.out.println(n + "is Prime Number");
}
else
{
System.out.println(n + "is not Prime Number");
}
}
}

Output:
E:\java>javac Testp.java
E:\java>java Testp
Welcome to Siddhartha Engineering College
Enter valid Number
7
7 is Prime Number

1
2. Write a Java program that works as a simple calculator. Use a grid layout to arrange
buttons for the digits and for the +, -,*, % operations. Add a text field to display the result.
Handle any possible exceptions like divide by zero.
Aim: Implement simple calculator using grid layout.
ALGORITHM:
Input: Press the values and operation in the calculator
Output: Displays the values in the text field
1 Start
2 take applet
3 add new Labels
4 call action performed method.
5 Check the type of operation.
6 Compute the Result.
7 Display the Result.
8 Stop
Program:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.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;
public JPanel 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);

2
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(ActionEvent ae)
{
String b = ae.getActionCommand();
switch (b)
{
case "1":

3
{
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;
case "8": {
v = v + "8";
tf1.setText(v);
}
break;
case "9": {
v = v + "9";
tf1.setText(v);
}
break;

4
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 "/": {
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="";

5
}
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 "/": {
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="";

6
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
break;
}
}
break;
}
}
}
public class Calc
{
public static void main(String[] args)
{
A a = new A();
}
}

Output:

7
3. a) Develop an applet that displays a simple message.
Aim: Implement Applet to display a simple message.
Algorithm:
Input: Enter the Message
Output: Displays the message in applet
Step1: start
Step 2: Create one class with Simple Applet
Step3: compute the data
Step 4: Display the Data
Step 5: Stop
PROGRAM:
import java.applet.Applet;
import java.awt.*;
public class Sms 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("Welcome To Siddhartha Eng College", 50, 50);
}
}
/*
<applet code=Sms.class height=300 width=400>
</applet>
*/

output:

8
3.b) Develop an Applet that receives an integer in one text field & compute its factorial value &
returns it in another text filed when the button “Compute” is clicked.
Aim: Implement an Applet program that calculates the factorial of a given number.

Algorithm:
Input: Value of „T1‟
Output: Compute the factorial value
Step1: Start.
Step2: Import java.awt pack, and relevant packages.
Step3: Import java.lang.string,awt. event,applet.Applet packages.
Step4: Create Class that extends Applet implements Action Listener
Step5: Create Buttons and Text Fields.
Step6: Create the Data. To set variables in the fields.
Step7: Compute the data.
Step8: Print the Data.(display)
Step9: Stop.
PROGRAM
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");
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);

9
}
public void actionPerformed(ActionEvent ae)
{
long n = Integer.parseInt(tf1.getText());
long f = 1;
while (n != 0)
{
f = f * n;
n--;
}
tf2.setText(String.valueOf(f));
}
}
/*
<applet code=Fact.class height=300 width=400>
</applet>
*/
Output:

10
4. Write a program that creates a user interface to perform integer divisions. The user enters two
numbers in the text fields, Num1 and Num2. The division of Num1 and Num2 is displayed in the
Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program
would throw a NumberFormatException. If Num2 were Zero, the program would throw an
Arithmetic Exception Display the exception in a message dialog box.
Aim: Implement a user interface to perform integer division and handle Arithmetic Exception.
Algorithm:
Input: Values of Text field T1, T2
Output: Displays the result in Text field T3
Step1: Start.
Step2: Import java.awt package
Step3: Import java.lang.string,awt. event,applet.Applet packages.
Step4: Create Class
Step5: Create Buttons and Text Fields.
Step6: Create the Data.
Step7: Perform the division.
Step8: Print the Data.
Step9: Stop.
PROGRAM:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class A extends JFrame implements ActionListener {
JLabel l1, l2, l3;
JTextField tf1, tf2, tf3;
JButton b1;
A() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
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);

11
b1 = new JButton("Divide");
add(b1);
b1.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent ae) {
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());
}
}
}
public class JavaApplication {
public static void main(String[] args) {
A a = new A();
}
}
Output:

12
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.
Aim: Implement multithreading concept using a simple application.

PROGRAM
import java.util.*;
class Even extends Thread
{
public int x;
public Even(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Thread Name:Even Thread and " + x + " is even Number and
Square of " + x + " is: " + x * x);
}
}
class Odd extends Thread
{
public int x;
public Odd(int x)
{
this.x = x;
}
public void run()
{
System.out.println("Thread Name:ODD Thread and " + x + " is odd number and
Cube of " + x + " is: " + x * x * x);
}
}
class A extends Thread
{
public Random r;
public void run() {
int num = 0;
r = new Random();
try {
for (int i = 0; i < 50; i++) {
num = r.nextInt(100);
System.out.println("Main Thread and Generated Number is " + num);
if (num % 2 == 0) {

13
Even t1=new Even(num);
t1.start();
} else {
Odd t2 = new Odd(num);
t2.start();
}
Thread.sleep(1000);
System.out.println("--------------------------------------");
}
} catch (Throwable ex) {
System.out.println(ex);
}
}
}
public class Mthread {
public static void main(String[] args) {
A a = new A();
a.start();
}
}
Output:

14
6). Write a Java program for the following:
i) Create a doubly linked list of elements.
ii) Delete a given element from the above list.
iii) Display the contents of the list after deletion.
PROGRAM
////////////////////////////////////////////////////////////////
class Link
{
public long dData; // data item
public Link next; // next link in list
public Link previous; // previous link in list
// -------------------------------------------------------------
public Link(long d) // constructor
{ dData = d; }
// -------------------------------------------------------------
public void displayLink() // display this link
{ System.out.print(dData + " "); }
// -------------------------------------------------------------
} // end class Link
////////////////////////////////////////////////////////////////
class DoublyLinkedList
{
private Link first; // ref to first item
private Link last; // ref to last item
// -------------------------------------------------------------
public DoublyLinkedList() // constructor
{
first = null; // no items on list yet
last = null;
}
// -------------------------------------------------------------
public boolean isEmpty() // true if no links
{ return first==null; }
// -------------------------------------------------------------
public void insertFirst(long dd) // insert at front of list
{
Link newLink = new Link(dd); // make new link

if( isEmpty() ) // if empty list,


last = newLink; // newLink <-- last
else
first.previous = newLink; // newLink <-- old first
newLink.next = first; // newLink --> old first
first = newLink; // first --> newLink
}

15
// -------------------------------------------------------------
public void insertLast(long dd) // insert at end of list
{
Link newLink = new Link(dd); // make new link
if( isEmpty() ) // if empty list,
first = newLink; // first --> newLink
else
{
last.next = newLink; // old last --> newLink
newLink.previous = last; // old last <-- newLink
}
last = newLink; // newLink <-- last
}
// -------------------------------------------------------------
public Link deleteFirst() // delete first link
{ // (assumes non-empty list)
Link temp = first;
if(first.next == null) // if only one item
last = null; // null <-- last
else
first.next.previous = null; // null <-- old next
first = first.next; // first --> old next
return temp;
}
// -------------------------------------------------------------
public Link deleteLast() // delete last link
{ // (assumes non-empty list)
Link temp = last;
if(first.next == null) // if only one item
first = null; // first --> null
else
last.previous.next = null; // old previous --> null
last = last.previous; // old previous <-- last
return temp;
}
// -------------------------------------------------------------
// insert dd just after key
public boolean insertAfter(long key, long dd)
{ // (assumes non-empty list)
Link current = first; // start at beginning
while(current.dData != key) // until match is found,
{
current = current.next; // move to next link
if(current == null)
return false; // didn't find it

16
}
Link newLink = new Link(dd); // make new link

if(current==last) // if last link,


{
newLink.next = null; // newLink --> null
last = newLink; // newLink <-- last
}
else // not last link,
{
newLink.next = current.next; // newLink --> old next
// newLink <-- old next
current.next.previous = newLink;
}
newLink.previous = current; // old current <-- newLink
current.next = newLink; // old current --> newLink
return true; // found it, did insertion
}
// -------------------------------------------------------------
public Link deleteKey(long key) // delete item w/ given key
{ // (assumes non-empty list)
Link current = first; // start at beginning
while(current.dData != key) // until match is found,
{
current = current.next; // move to next link
if(current == null)
return null; // didn't find it
}
if(current==first) // found it; first item?
first = current.next; // first --> old next
else // not first
// old previous --> old next
current.previous.next = current.next;

if(current==last) // last item?


last = current.previous; // old previous <-- last
else // not last
// old previous <-- old next
current.next.previous = current.previous;
return current; // return value
}
// -------------------------------------------------------------
public void displayForward()
{
System.out.print("List (first-->last): ");

17
Link current = first; // start at beginning
while(current != null) // until end of list,
{
current.displayLink(); // display data
current = current.next; // move to next link
}
System.out.println("");
}
// -------------------------------------------------------------
public void displayBackward()
{
System.out.print("List (last-->first): ");
Link current = last; // start at end
while(current != null) // until start of list,
{
current.displayLink(); // display data
current = current.previous; // move to previous link
}
System.out.println("");
}
// -------------------------------------------------------------
} // end class DoublyLinkedList
////////////////////////////////////////////////////////////////
class DoublyLinkedApp
{
public static void main(String[] args)
{ // make a new list
DoublyLinkedList theList = new DoublyLinkedList();

theList.insertFirst(22); // insert at front


theList.insertFirst(44);
theList.insertFirst(66);

theList.insertLast(11); // insert at rear


theList.insertLast(33);
theList.insertLast(55);

theList.displayForward(); // display list forward


theList.displayBackward(); // display list backward

theList.deleteFirst(); // delete first item


theList.deleteLast(); // delete last item
theList.deleteKey(11); // delete item with key 11

theList.displayForward(); // display list forward

18
theList.insertAfter(22, 77); // insert 77 after 22
theList.insertAfter(33, 88); // insert 88 after 33

theList.displayForward(); // display list forward


} // end main()
} // end class DoublyLinkedApp
////////////////////////////////////////////////////////////////

Output:
E:\JAVA>javac DoublyLinkedApp.java

E:\JAVA>java DoublyLinkedApp
List (first-->last): 66 44 22 11 33 55
List (last-->first): 55 33 11 22 44 66
List (first-->last): 44 22 33
List (first-->last): 44 22 77 33 88

19
7) Write a java program that simulates a traffic light. The program lets the user select one of three
lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate message
with “stop” or “ready” or “go” should appear above the buttons in a selected color. Initially there
is no message shown.
Aim: Implement traffic light using AWT layouts.
PROGRAM
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class A extends JFrame implements ItemListener {
public JLabel l1, l2;
public JRadioButton r1, r2, r3;
public ButtonGroup bg;
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();
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);

20
bg.add(r3);
setVisible(true);
}
public void itemStateChanged(ItemEvent i) {
JRadioButton jb = (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) {
A a = new A();
}
}

Output:

21
8) Write a java program to create an abstract class named Shape that contains two integers and an
empty method named printArea(). Provide three classes named Rectangle, Triangle and Circle
such that each one of the classes extends the class Shape. Each one of the classes contain only the
method printArea( ) that prints the area of the given shape.
Aim: Implement abstract class using the concept of inheritance.

Algorithm:
Input: Creates GUI
Output: number of sides a triangle, trapezoid and Hexagon
1: Start.
2: Create one abstract Class Shape with method numberofSides().
3: Create classes triangle, trapezoid and Hexagon which will extend Shape.
4: Implement the method “numberofSides()” in each class.
5: Create class cointating main().
6: Display each class method.
7: Stop the Program.
PROGRAM

abstract class Shape {


public int x, y;
public abstract void printArea();
}
class Rectangle extends Shape {
public void printArea() {
System.out.println("Area of Rectangle is " + x * y);
}
}
class Triangle extends Shape {
public void printArea() {
System.out.println("Area of Triangle is " + (x * y) / 2);
}
}
class Circle extends Shape {
public void printArea() {
System.out.println("Area of Circle is " + (22 * x * x) / 7);
}
}
public class Abstex {
public static void main(String[] args) {
// TODO code application logic here
Rectangle r = new Rectangle();
r.x = 10;
r.y = 20;
r.printArea();
System.out.println("-------------------------------------");

22
Triangle t = new Triangle();
t.x = 30;
t.y = 35;
t.printArea();
System.out.println("-------------------------------------");
Circle c = new Circle();
c.x = 2;
c.printArea();
System.out.println("-------------------------------------");
}
}
Output:

23
9) Suppose that a table named Table.txt is stored in a text file. The first line in the file header and
the remaining lines correspond to row in the table. The elements are separated by commas. Write
a Java program to display the table using labels in grid layout.
Aim: Display the content of a text file using tables in grid layout.

Algorithm:
Input: Enter the text file
Output: Displays the text file information in Table
1: Start.
2: Import all relevant packages
3: Create a Class which extends JFrame class.
4: Create init process for initialization
5: Create and initialize column headings
6: Initialize the data
7: create the table
8: Add the table to a scroll pane
9: add the scroll pane to the content pane
10: Display the table contents
11: Stop
PROGRAM:
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class A extends JFrame {
public A() {
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout g = new GridLayout(0, 3);
setLayout(g);
try {
FileInputStream fin = new FileInputStream("E:\\emp.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 JLabel(i));
}
}
} catch (Exception ex) {

24
}
setDefaultLookAndFeelDecorated(true);
pack();
setVisible(true);
}
}
public class Tbl {
public static void main(String[] args) {
A a = new A();
}
}
Output:

25
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).
Aim: Implement all mouse events using adapter classes.

PROGRAM:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<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;

26
msg="Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
mx=40;
my=80;
msg="Mouse Exited";
repaint();
}
public void mouseDragged(MouseEvent me)
{
mx=me.getX();
my=me.getY();
showStatus("Currently mouse dragged"+mx+" "+my);
repaint();
}
public void mouseMoved(MouseEvent me)
{
mx=me.getX();
my=me.getY();
showStatus("Currently mouse is at"+mx+" "+my);
repaint();
}
public void paint(Graphics g)
{
g.drawString("Handling Mouse Events",30,20);
g.drawString(msg,60,40);
}}
Output:

27
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)
Aim: Implement a program to display the content of a text file using hash tables.

ALGORITHM:
Input: Enter the text file
Output: Displays all the data using hash table
1. Start the program.
2. Import the packages of Io.BufferdReader, io.File, io.FileNotFoundException, io.FileReader,
IOException, util.HashTable, utilIterator, util.Set.
3. Create classes, methods.
4. Create Hash Table and store the data in Hash table from file.
5. Use Iterator interface to search the value.
6. After getting the input value print the other value from Hash Table.
7. Print the output.
8. Stop the Program.
Program:
import java.util.*;
import java.io.*;
public class Hashtbl {
public static void main(String[] args) {
try {
FileInputStream fs = new FileInputStream("E:\\ph.txt");
Scanner sc = new Scanner(fs).useDelimiter("\\s+");
Hashtable<String, String> ht = new Hashtable<String, String>();
String[] arrayList;
String a;
System.out.println("HASH TABLE IS");
System.out.println("--------------------------");
System.out.println("KEY : VALUE");
while (sc.hasNext()) {
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);

28
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 (@SuppressWarnings("rawtypes") Map.Entry e : ht.entrySet()) {
if (mobile.equals(e.getValue())) {
System.out.println("Name is " + e.getKey());
}
}
} else {
System.out.println("Not Found");
}
}
break;
case "3": {
opt = "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());
}
}
}

29
Output:

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

Program:
// A correct implementation of a producer and consumer.
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n) {
while(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;

31
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
class PCFixed {
public static void main(String args[]) {
Q q = new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}

Output:

E:\JAVA>java PCFixed
Put: 0
Press Control-C to stop.
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

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

Program:
import java.io.File;
import java.io.IOException;

public class RecursiveFileDisplay {

public static void main(String[] args) {


File currentDir = new File("."); // current directory
displayDirectoryContents(currentDir);
}

public static void displayDirectoryContents(File dir) {


try {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
System.out.println("directory:" + file.getCanonicalPath());
displayDirectoryContents(file);
} else {
System.out.println(" file:" + file.getCanonicalPath());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

}
Output:
E:\JAVA>javac RecursiveFileDisplay.java

E:\JAVA>java RecursiveFileDisplay
file:E:\JAVA\-uploads-Notes-btech-5sem-cse-Java Notes - Applet-AWT-Event Handling.pdf
file:E:\JAVA\A$B$C.class
file:E:\JAVA\A$B.class
file:E:\JAVA\A$D.class
file:E:\JAVA\A$Message.class
file:E:\JAVA\A.class
file:E:\JAVA\A.java

33
14). Write a Java program that implements Quick sort algorithm for sorting a list of names
in ascending order:
/**
** Java Program to Implement Quick Sort
**/

import java.util.Scanner;

/** Class QuickSort **/


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

/** partition **/


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

i++;
j--;
}
}

/** recursively sort lower half **/

34
if (low < j)
quickSort(arr, low, j);
/** recursively sort upper half **/
if (i < high)
quickSort(arr, i, high);
}
/** Main method **/
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Quick Sort Test\n");
int n, i;
/** Accept number of elements **/
System.out.println("Enter number of Strings to be sorted");
n = scan.nextInt();
/** Create array of n elements **/
String[] arr=new String[n];
/** Accept elements **/
System.out.println("\nEnter "+ n +" Strings");
for (i = 0; i < n; i++)
arr[i] = scan.next();
/** Call method sort **/
sort(arr);
/** Print sorted Array **/
System.out.println("\n Strings after sorting ");
for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
Output:

D:\JAVA>javac QuickSort.java

D:\JAVA>javac QuickSort.java
D:\JAVA>java QuickSort
Quick Sort Test
Enter number of Strings to be sorted
5
Enter 5 Strings
ramana mahesh arun suresh abhi
Strings after sorting
abhi arun mahesh ramana suresh

35
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.
Program:

public class BubbleSortDescendingOrderDemo


{
public static void main(String a[])
{
//Numbers which need to be sorted
int numbers[] = {23,5,27,1,7,12,3,34,0};
//Displaying the numbers before sorting
System.out.print("Before sorting, numbers are ");
for(int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i]+" ");
}
System.out.println();
//Sorting in descending order using bubble sort
bubbleSortInDescendingOrder(numbers);
//Displaying the numbers after sorting
System.out.print("After Sorting, numbers are ");
for(int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i]+" ");
}
}
//This method sorts the input array in desecnding order
public static void bubbleSortInDescendingOrder(int numbers[])
{
int temp;
int count=0;
for(int i = 0; i < numbers.length; i++)
{
for(int j = i+1; j < (numbers.length-1); j++)
{
//if numbers[j-1] < numbers[j], swap the elements
if(numbers[i] < numbers[j])
{
temp = numbers[j];
numbers[j]=numbers[i];
numbers[i]=temp;
count++;
}
}
}

36
System.out.println("Total Number of inter changes:"+count);
}
}

Output:
E:\JAVA>javac BubbleSortDescendingOrderDemo.java

E:\JAVA>java BubbleSortDescendingOrderDemo
Before sorting, numbers are 23 5 23 1 7 12 3 34 0
Total Number of inter changes: 14
Before sorting, numbers are 34 23 23 12 7 5 3 1 0

37

You might also like