R22 - OOPS Using JAVA Lab Manual 2-2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

JAVA PROGRAMMING LAB MANUAL

WEEK-1

1. Aim: 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, autofill. Try code formatter and code refactoring like renaming
variables, methods and classes. Try debug step by step with a small program of
about 10 to 15 lines which contains at least one if else condition and a for loop.

Program:

import java.util.*;
public class Testproject {
public static void main(String[] args) {
System.out.println("MALLA REDDY COLLEGE OF ENGINEERING FOR
WOMEN");
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 (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");
}
}
}

1
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Output:

2
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

WEEK-2

2. Aim: 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.

Program:

import javax.swing.*;

import javax.swing.event.*;

import java.awt.*;

import java.awt.event.*;

class A5 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 A5() {

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

3
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

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

4
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

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

5
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

public void actionPerformed(ActionEvent ae) {

String b = ae.getActionCommand();

switch (b) {

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

6
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

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;

case "0": {

v = v + "0";

7
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

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 = "";

8
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

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

9
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

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) {

10
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

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 Calculator{

public static void main(String[] args) {

A5 a = new A5();

}}

11
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Output:

12
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

13
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Viva Questions

1) What are Looping Statements?


2) What is Layout Manager?
3) What are the different types of layout manager?
4) How do you raise an exception when a number is divided by zero?
5) What are the basic operations of a calculator

14
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

WEEK-3

3. a. Aim: Develop an applet in java that displays a simple message.

Program:

import java.applet.*;

import java.awt.*;

/*<applet code="Apppletlifecycle.class" width=200 height=200>

</applet>*/

public class Apppletlifecycle extends Applet

public void init()

public void start()

public void stop()

public void destroy()

public void paint(Graphics g)

g.drawString("welcome to applet program",50,50);

15
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Output:

16
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

b. Aim: Develop an applet in java that receives an integer in one textfield, and
computes its factorial value and returns it in another text field, when the button
named “Compute” is clicked.

Program:

import java.lang.*;

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

/*<applet code="Factorial.class" width=180 height=300></applet>*/

public class Factorial extends Applet implements ActionListener

Button compute;

TextField fact,num;

Label l1,l2;

public void init()

l1=new Label("NUMBER:",Label.RIGHT);

l2=new Label("FACTORIAL:",Label.RIGHT);

compute=new Button("compute");

num=new TextField(40);

fact=new TextField(10);

add(l1);

add(num);

add(l2);

add(fact);

add(compute);

17
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

num.addActionListener(this);

fact.addActionListener(this);

compute.addActionListener(this);

public void actionPerformed(ActionEvent ae)

String msg=ae.getActionCommand();

if(msg.equals("compute"))

int f=1;

String str=num.getText();

int n=Integer.parseInt(str);

for(int i=1;i<=n;i++)

f=f*i;

String str1=String.valueOf(f);

fact.setText(str1);

repaint();

}}

public void paint(Graphics g)

}}

Output:

18
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Viva Questions

1) What is an applet?
2) What are the different types of applets available in java?
3) Why it is not possible to use remote applet than local applet?
4) What are the different ways of creating a button, label, text field?
5) What is the use of Graphics Class?

19
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

WEEK-4

4. Aim: Write a java program that creates a user interface to perform integer
divisions. The user enters two numbers in the textfields, 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
Number Format Exception. If Num2 were zero, the program would throw an
Arithmetic Exception. Display the exception in a message dialog box.

Program:

import java.lang.*;

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

/*<applet code="Division.class" width=180 height=300></applet>*/

public class Division extends Applet implements ActionListener

Button div;

TextField result,Num1,Num2;

Label l1,l2,l3;

String msg1;

public void init()

l1=new Label("NUMBER1",Label.RIGHT);

l2=new Label("NUMBER2",Label.RIGHT);

l3=new Label("RESULT",Label.RIGHT);

div=new Button("DIVIDE");

result=new TextField(40);

Num1=new TextField(10);

20
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Num2=new TextField(10);

add(l1);

add(Num1);

add(l2);

add(Num2);

add(l3);

add(result);

add(div);

div.addActionListener(this);

Num1.addActionListener(this);

Num2.addActionListener(this);

result.addActionListener(this);

public void actionPerformed(ActionEvent ae)

try

String msg=ae.getActionCommand();

String str1=Num1.getText();

int n1=Integer.parseInt(str1);

String str2=Num2.getText();

int n2=Integer.parseInt(str2);

int f=n1/n2;

String str;

str=String.valueOf(f);

21
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

result.setText(str);

catch(ArithmeticException e)

result.setText("ARITHMETIC EXCEPTION");

catch(NumberFormatException e)

result.setText("NUMBER FORMAT EXCEPTION");

repaint();

public void paint(Graphics g)

}}

22
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Output:

Viva Questions

1) What is an exception?
2) What is the super class of all exception classes?
3) When does an number format exception occurs?
4) What are the different exceptions available in java programming language?
5) What is the difference between Interface and a class?

23
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

WEEK-5

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

Program:

import java.util.*;
class even implements Runnable {
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 implements Runnable {
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 String tname;
public Random r;
public Thread t1, t2;
public A(String s) {
tname = s;
}
public void run() {
int num = 0;
r = new Random();
try {
24
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

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) {
t1 = new Thread(new even(num));
t1.start();
} else {
t2 = new Thread(new odd(num));
t2.start();
}
Thread.sleep(1000);
System.out.println(" ");
}
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
public class Mthread {
public static void main(String[] args) {
A a = new A("One");
a.start();
}
}

25
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Output:

Viva Questions

1) What is a Thread ?
2) What are the different ways of using threads?
3) What is the difference between Runnable and Thread?
4) Explain the life cycle of a thread?
5) What is the difference between Stop and Wait?

26
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

WEEK-6

6. Aim: 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:

import java.io.*;

import java.util.*;

class Node{

public int data;

public Node next;

public Node prev;

class DLL{

public Node head;

public DLL(){

head=null;

public Node create(int val, Node New){

Node temp;

temp=head;

if(New==null)

System.out.println("\n memory is not allocated");

New.data=val;

if(head==null){

head=New;

27
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

temp=head;

else{

while(temp.next!=null)

temp=temp.next;

temp.next=New;

New.prev=temp;

temp=New;

return head;

public void display(Node head)throws NullPointerException{

Node temp;

temp=head;

if(temp==null){

System.out.println("\n The list is empty \n");

return;

System.out.println("The doubly linked list in forward direction is...");

while(temp!=null){

System.out.print(" "+temp.data);

temp=temp.next;

System.out.println("\n The doubly linked list in reverse direction is...");

temp=head;

28
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

while(temp.next!=null)

temp=temp.next;

while(temp!=null){

System.out.print(" "+temp.data);

temp=temp.prev;

Node search(Node head,int key){

Node temp;

int found=0;

temp=head;

if(temp==null){

System.out.println("The linked list is empty");

return null;

while(temp!=null && found==0){

if(temp.data!=key)

temp=temp.next;

else

found=1;

if(found==1){

return temp;

else{

29
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

return null;

public Node dele(Node head,int key)throws NullPointerException{

Node temp,temp_prev;

temp=head;

if(temp==null){

System.out.println("\n The list is empty. Can not delete");

return null;

temp=search(head,key);

if(temp!=null){

temp_prev=temp.prev;

if(temp_prev!=null){

if(temp.next==null){

temp_prev.next=null;

temp=null;

else{

temp_prev.next=temp.next;

(temp.next).prev=temp_prev;

temp.next=null;

temp=null;

30
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

else{

if(temp.next==null&&temp.prev==null)

return null;

head=temp.next;

head.prev=null;

temp=null;

System.out.println("\t the element is deleted!!!");

return head;

class DLLDemo{

public static void main(String ar[])throws IOException,NullPointerException{

int choice,val,key;

char ans='y';

DLL obj=new DLL();

Scanner input=new Scanner(System.in);

do{

System.out.println("\n Program to perform various operations on doubly linked list");

System.out.println("1.Create");

System.out.println("2.Display");

System.out.println("3.Delete an element from list");

System.out.println("\n Enter your choice: ");

31
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

choice=input.next().charAt(0);

switch(choice){

case '1': System.out.println("enter the element: ");

val=input.nextInt();

Node New=new Node();

New.next=null;

New.prev=null;

obj.head=obj.create(val,New);

break;

case '2': obj.display(obj.head);

break;

case '3': System.out.println("\n Enter the element to be deleted from the linked list:
");

key=input.nextInt();

obj.head=obj.dele(obj.head,key);

obj.display(obj.head);

break;

System.out.println("\n Do you want to go to main menu(y/n)?");

ans=input.next().charAt(0);

}while(ans=='y');

32
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Output:

Viva Questions:
1. Define Doubly linked list?
2. How to display the multiple cases?
3. What are the control statements?
4. What are the transfer statements available in the application?
5. Difference between singly linked list and doubly linked list?

33
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

WEEK-7

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

Program:

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

/*<applet code="Traffic.class" width=180 height=300></applet>*/

public class Traffic extends Applet implements ItemListener

Frame t=new Frame();

Checkbox red,orange,green;

CheckboxGroup cg;

public void start()

public void stop()

public void destroy()

public void paint(Graphics g)

34
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

g.drawRect(10,10,100,180);

g.drawOval(45,15,50,50);

g.drawOval(45,67,50,50);

g.drawOval(45,119,50,50);

if(red.getState()==true)

g.setColor(Color.red);

g.fillOval(45,15,50,50);

if(orange.getState()==true)

g.setColor(Color.orange);

g.fillOval(45,67,50,50);

if(green.getState()==true)

g.setColor(Color.green);

g.fillOval(45,119,50,50);

public void init()

cg=new CheckboxGroup();

red=new Checkbox("red",cg,false);

35
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

orange=new Checkbox("orange",cg,false);

green=new Checkbox("green",cg,false);

add(red);

add(orange);

add(green);

red.reshape(60,250,30,30);

orange.reshape(90,250,30,30);

green.reshape(120,250,30,30);

red.addItemListener(this);

orange.addItemListener(this);

green.addItemListener(this);

public void itemStateChanged(ItemEvent ie)

repaint();

public static void main(String args[])

Traffic t1=new Traffic();

36
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Output:

Viva Questions

1) What is an applet ?
2) What is the difference between an application and an applet?
3) How do you run an applet application?
4) How do use threads in an applet?
5) What is an life cycle of an applet ?

37
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

WEEK-8

8. Aim: 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 contains only the method printArea() that prints the
area of the given shape.

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
{
/**
* @param args the command line arguments
*/
38
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

public static void main(String[] args)


{
// TODO code application logic here
Rectangle r = new Rectangle();
r.x = 10;
r.y = 20;
r.printArea();
Triangle t = new Triangle();
t.x = 30;
t.y = 35;
t.printArea();
Circle c = new Circle();
c.x = 2;
c.printArea();
}
}

Output:

Area of Rectangle is 200

Area of Triangle is 525

Area of Circle is 12

Viva Questions

1) What is an abstract class?


2) What is the difference between abstract class and an class?
3) Can an abstract class have Static variable? If, yes justify
4) How do you use an already defined abstract class?
5) What is the difference between extends and implements?

39
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

WEEK-9

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

Program:

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

con.setLayout(new BorderLayout());

final String[] colHeads={"Name","Roll Number","Department","Percentage"};

40
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

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("Eception raised" +e.toString());

table1=new JTable(data,colHeads);

41
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

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[])

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

Output:

42
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Viva Questions

1) What is layout manager?


2) What are the different types of layout managers available in java?
3) What is the difference between Grid layout and Grid Bag Layout?
4) How do you display a table using grid layout in java?
5) What is the use of JFrame.EXIT_ON_CLOSE?

43
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

WEEK-10

10. Aim: Write a java program that handles all mouse events and shows the event
name at the center of the window when a mouse is fired.

Program:

import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
/*<applet code="Mouseevents"width=200 height=100>
</applet>*/
public class Mouseevents extends Applet implements
MouseListener,MouseMotionListener
{
String msg="";
int x=0,y=0;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}
public void mouseClicked(MouseEvent me)
{
x=10;
y=20;
msg="mouse clicked";
repaint();
}
public void mouseEntered(MouseEvent me)
{
x=10;
y=20;
msg="mouse entered";
repaint();
}
public void mouseExited(MouseEvent me)
{
x=10;
y=20;
msg="mouse exited";
repaint();

44
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

}
public void mousePressed(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="down";
repaint();
}
public void mouseReleased(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="up";
repaint();
}
public void mouseDragged(MouseEvent me)
{
x=me.getX();
y=me.getY();
msg="*";
showStatus("dragging mouse at"+x+","+y);
repaint();
}
public void mouseMoved(MouseEvent me)
{
showStatus("moving mouse at"+me.getX()+","+me.getY());
}
public void paint(Graphics g)
{
g.drawString(msg,x,y);
}
}

45
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Output:

Viva Questions

1. What is an Event? When does an Event occur?


2. What are the different types of event available in java?
3. What are the difference between Mouse events and Key Events?
4. What are the different types of methods available in Mouse Listener Interface?
5. What is the difference between List and an Interface?

46
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

WEEK-11

11. Aim: 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.

Program:

import java.util.*;

import java.io.*;

public class Hashtbl

public static void main(String[] args)

try

FileInputStream fs = 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");

System.out.println("HASH TABLE IS");

System.out.println("-------------------------- ");

System.out.println("KEY : VALUE");

while (sc.hasNext()) {

a = sc.nextLine();

arrayList = a.split("\\s+");
47
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

ht.put(arrayList[0], arrayList[1]);

System.out.println(arrayList[0] + ":" + arrayList[1]);

System.out.println("Welcome");

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;

48
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

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

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

49
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

System.out.println(ex.getMessage());

}}

Output:

50
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Viva Questions

1) What are collection classes available in java?


2) What is Hash Table?
3) Why do you need to go for Hash table than to use Arrays?
4) What is the difference between Contains Key and Contains Str ?
5) What is the difference between hasNext and has methods?

51
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

WEEK-12

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

Program:

class Producer implements Runnable{

InterThread obj;

Producer(InterThread obj){

this.obj=obj;

new Thread(this,"Producer").start();

public void run(){

for(int i=0;i<10;i++){

obj.put(i);

class Consumer implements Runnable{

InterThread obj;

Consumer(InterThread obj){

this.obj=obj;

new Thread(this, "Consumer").start();

public void run(){

for(int i=0;i<10;i++){

obj.get();

52
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

class InterThread{

int n;

boolean flag=false;

synchronized int get(){

if(!flag)

try{

wait();

catch(InterruptedException ie){

System.out.println("Interrupted Exception");

System.out.println("Consumer Consuming:"+n);

flag=false;

notify();

return n;

synchronized void put(int n){

if(flag)

try{

wait();

catch(InterruptedException ie){

53
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

System.out.println("InterruptedException");

this.n=n;

flag=true;

System.out.println("Producer producing"+n);

notify();

public static void main(String ar[]){

InterThread t=new InterThread();

new Producer(t);

new Consumer(t);

54
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Output:

Viva Questions

1) What is a Thread?
2) Define Synchronization?
3) Define InterThread Communication?
4) Thread Priorities.
5) Thread Model.

55
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

WEEK-13

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

Program:

import java.io.*;

public class FileDisplay{

public static void main(String ar[]){

File DirName=new File(ar[0]);

displayContents(DirName);

public static void displayContents(File dir){

try{

File[] list=dir.listFiles();

for(File file:list){

if(file.isDirectory()){

System.out.println("directory:"+file.getCanonicalPath());

displayContents(file);

else{

System.out.println(" file:"+file.getCanonicalPath());

catch(IOException ie){

ie.printStackTrace();

56
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

Output:

Viva Questions

1) What is the use of File Input Stream?


2) What is the use of File?
3) What is the need for Directory?
4) What is the use of try catch block?
5) What is the difference between file and directory?

57
MALLA REDDY COLLEGE OF ENGINEERING FOR WOMEN R-22 OOPS THROUGH JAVA LAB MANUAL

58

You might also like