0% found this document useful (0 votes)
13 views35 pages

Java Programming Lab Exercises

The document outlines a Java programming lab for B.Tech. II Year I Sem, covering various topics including creating a test project, developing a simple calculator, applets for displaying messages and computing factorials, handling exceptions in division operations, implementing multi-threading, and managing a doubly linked list. Each section includes example code snippets and expected outputs for practical understanding. The lab emphasizes hands-on experience with Java programming concepts and user interface design.

Uploaded by

ponugotidivya8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views35 pages

Java Programming Lab Exercises

The document outlines a Java programming lab for B.Tech. II Year I Sem, covering various topics including creating a test project, developing a simple calculator, applets for displaying messages and computing factorials, handling exceptions in division operations, implementing multi-threading, and managing a doubly linked list. Each section includes example code snippets and expected outputs for practical understanding. The lab emphasizes hands-on experience with Java programming concepts and user interface design.

Uploaded by

ponugotidivya8
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

1. Use Eclipse or Net bean platform and acquaint yourself 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.

import [Link].*;
public class TestProject
{
public static void main(String[] args)
{
[Link]("Program to check given number is Prime or Not");
Scanner sc = new Scanner([Link]);
[Link]("Enter a +ve Number ");
int n = [Link]();
int count=0;
for (int i = 1; i <= n; i++)
{
if (n % i == 0)
{
count++;
}
}
if (count == 2)
{
[Link](n +" is a Prime Number");
}
else
{
[Link](n +" is not a Prime Number");
}
}
}

Output1:

Program to check given number is Prime or Not


Enter a +ve Number 4
4 is not a Prime Number

Output2:

Program to check given number is Prime or Not


Enter a +ve Number 5
5 is a Prime Number

1|Page
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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.

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;

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); [Link](tf1);
add(p);
setLayout(new GridLayout(0, 3));
b1 = new JButton("1");
[Link](this);
add(b1);
b2 = new JButton("2");
[Link](this);
add(b2);
b3 = new JButton("3");
[Link](this);
add(b3);
b4 = new JButton("4");
[Link](this);
add(b4);
b5 = new JButton("5");
[Link](this);
add(b5);
b6 = new JButton("6");
[Link](this);
add(b6);
b7 = new JButton("7");
[Link](this);
add(b7);
b8 = new JButton("8");
[Link](this);
add(b8);
b9 = new JButton("9");

2|Page
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

[Link](this);
add(b9);
b10 = new JButton("0");
[Link](this);
add(b10);
b11 = new JButton("+");
[Link](this);
add(b11);
b12 = new JButton("-");
[Link](this);
add(b12);
b13 = new JButton("*");
[Link](this);
add(b13);
b14 = new JButton("/");
[Link](this);
add(b14);
b16 = new JButton("%");
[Link](this);
add(b16);
b15 = new JButton("=");
[Link](this);
add(b15);
setVisible(true);
}

public void actionPerformed(ActionEvent ae)


{
String b = [Link]();
long i ;
switch (b)
{
case "1":
v = v + "1";
[Link](v);
break;
case "2":
v = v + "2";
[Link](v);
break;
case "3":
v = v + "3";
[Link](v);
break;
case "4":
v = v + "4";
[Link](v);
break;
case "5":
v = v + "5";

3|Page
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

[Link](v);
break;
case "6":
v = v + "6";
[Link](v);
break;
case "7":
v = v + "7";
[Link](v);
break;
case "8":
v = v + "8";
[Link](v);
break;
case "9":
v = v + "9";
[Link](v);
break;
case "0":
v = v + "0";
[Link](v);
break;
case "+":
op = "+";
v1 = [Link]();
v = "";
break;
case "-":
op = "-";
v1 = [Link]();
v = "";
break;
case "*":
op = "*";
v1 = [Link]();
v = "";
break;
case "/":
op = "/";
v1 = [Link]();
v = "";
break;
case "%":
op = "%";
v1 = [Link]();
v = "";
break;
case "=":
switch (op)
{

4|Page
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

case "+":
v = [Link]();
if ([Link](""))
{
v = "0";
}
i = [Link](v1) + [Link](v);
[Link]([Link](i));
v="";
break;
case "-":
v = [Link]();
if ([Link](""))
{
v = "0";
}
i = [Link](v1) - [Link](v);
[Link]([Link](i));
v="";
break;
case "*":
v = [Link]();
if ([Link](""))
{
v = "0";
}
i = [Link](v1) * [Link](v);
[Link]([Link](i));
v="";
break;
case "/":
try
{
v = [Link]();
if ([Link](""))
{
v = "0";
}
i =[Link](v1) / [Link](v);
[Link]([Link](i));
v="";
}
catch (Exception ex)
{
[Link](this, [Link]());
}
break;
case "%":
try
{

5|Page
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

v = [Link]();
if ([Link](""))
{
v = "0";
}
i=[Link](v1)%[Link](v);
[Link]([Link](i));
v="";
}
catch (Exception ex)
{
[Link](this,[Link]());
}
break;
}
}
}
}

public class Calculator


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

Output:

6|Page
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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.

A) Develop an applet in Java that displays a simple message


import [Link].*;
import [Link].*;

public class AppletMsg extends Applet


{
public void paint(Graphics g)
{
[Link]([Link]);
Font font = new Font("Comic Sans MS", [Link], 15);
[Link](font);
[Link]("Welcome Krishna!",50, 50);
}
}

/*
<applet code="AppletMsg" width=400 height=200>
</applet>
*/

Output:

7|Page
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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.

import [Link];
import [Link].*;
import [Link].*;
public class FactApplet extends Applet implements ActionListener
{
Label l1, l2, l3;
TextField tf1, tf2;
Button b1;
public void init()
{
setSize(400, 200);
FlowLayout f = new FlowLayout();
setLayout(f);
l1 = new Label("Enter Value");
[Link]([Link]);
add(l1);
tf1 = new TextField(5);
[Link]("0");
add(tf1);
b1 = new Button("Compute");
[Link](this);
add(b1);
l3 = new Label();
add(l3);
l2 = new Label("factorial: ");
[Link]([Link]);
add(l2);
tf2 = new TextField(5);
add(tf2);
}
public void actionPerformed(ActionEvent ae)
{
long n = [Link]([Link]());
long f = 1;
while (n != 0)
{
f = f * n;
n--;
}
[Link]([Link](f));
}
}

/*
<applet code="FactApplet" width=45 height=54>
</applet>
*/

8|Page
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

Output:

9|Page
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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.

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Division extends JFrame implements ActionListener
{
JLabel l1, l2, l3;
JTextField tf1, tf2, tf3;
JButton b1;
Division( )
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
l1 = new JLabel("Welcome");
setSize(800, 400);
l1 = new JLabel("Enter First Number");
add(l1);
tf1 = new JTextField(10);
add(tf1);
l2 = new JLabel("Enter Second Number");
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);
[Link](this);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
try
{
int a = [Link]([Link]());
int b = [Link]([Link]());
if(b==0)
throw new ArithmeticException("Division by Zero Error");
float c = (float) a / b;
[Link]([Link](c));
}
catch (NumberFormatException ex)

10 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

{
[Link](this, [Link]());
}
catch (ArithmeticException ex)
{
[Link](this, [Link]());
}
}
}
public class DivisionApp
{
public static void main(String[] args)
{
Division d = new Division ();
}
}

Output:

11 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

12 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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

import [Link].*;
class Even implements Runnable
{
public int x;
public Even(int x)
{
this.x = x;
}
public void run( )
{
[Link]("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( )
{
[Link]("ODD Thread and " + x + " is odd number and Cube of " + x + " is: " + x * x * x);
}
}
class MainThread extends Thread
{
public String tname;
public Random r;
public Thread t1, t2;
public MainThread(String s)
{
tname = s;
}
public void run( )
{
int num = 0;
r = new Random( );
try
{
for (int i = 0; i < 10; i++)
{
num = [Link](100);
[Link]("Main Thread and Generated Number is " + num);
if (num % 2 == 0)

13 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

{
t1 = new Thread(new Even(num));
[Link]();
}
else
{
t2 = new Thread(new Odd(num));
[Link]();
}
[Link](1000);
[Link](" -------------------------------------- ");
}
}
catch (Exception ex)
{
[Link]([Link]());
}
}
}
public class MultiThread
{
public static void main(String[] args)
{
MainThread mt = new MainThread("Main");
[Link]();
}
}

Output:

14 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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.

import [Link].*;
class Node
{
public int x;
public Node next;
public Node prev;
}
class DoubleLinkedList
{
public Node first;
public Node last;
DoubleLinkedList()
{
first=new Node();
[Link]=null;
[Link]=null;
last=first;
}
void add (int v)
{
Node temp=new Node();
temp.x=v;
[Link]=null;
[Link]=temp;
[Link]=last;
last=temp;
}
void insert(int p,int v)
{
Node ptr=first,temp;
for(int i=1;i<=p-1;i++)
ptr=[Link];
if([Link]==null)
add(v);
else
{
temp=new Node();
temp.x=v;
[Link]=[Link];
[Link]=temp;
[Link]=temp;
[Link]=ptr;
}
}
void del(int p)

15 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

{
Node ptr=first,temp;
for(int i=1;i<=p-1;i++)
ptr=[Link];
if([Link]==null)
{
temp=last;
last=[Link];
[Link]=null;
}
else
{
temp=[Link];
[Link]=[Link];
[Link]=ptr;
}
temp=null;
}
void show()
{
[Link]("\nList Elements from Left to Right: ");
for(Node ptr=[Link];ptr!=null;ptr=[Link])
[Link]("=>"+ptr.x);
}
}
class DLList
{
public static void main(String args[]) throws Exception
{
String con="";
int x,op,p,v;
DoubleLinkedList l1=new DoubleLinkedList();
InputStreamReader isr=new InputStreamReader([Link]);
BufferedReader br=new BufferedReader(isr);
[Link]("Enter elements to create");
do
{
x=[Link]([Link]());
[Link](x);
[Link]("Do you want to add more elements (y/n):");
con=[Link]();
}
while([Link]("y"));
[Link]();
do
{
[Link]("\n [Link]\n [Link] \n [Link] \n [Link]");
[Link]("\nSelect an option:");
op=[Link]([Link]());
if(op==1)

16 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

{
[Link]("Enter Position to insert:");
p= [Link]([Link]());
[Link]("Enter Value to insert:");
v= [Link]([Link]());
[Link](p,v);
}
if(op==2)
{
[Link]("Enter Position to delete:");
p= [Link]([Link]());
[Link](p);
}
[Link]();
}while(op<4);
}
}

Output:
D:\Record25>javac [Link]

D:\Record25>java DLList
Enter elements to create
11
Do you want to add more elements (y/n):y
22
Do you want to add more elements (y/n):y
33
Do you want to add more elements (y/n):n

List Elements from Left to Right:


=>11=>22=>33
[Link]
[Link]
[Link]
[Link]

Select an option:
1
Enter Position to insert:
4
Enter Value to insert:
44

List Elements from Left to Right:


=>11=>22=>33=>44
[Link]
[Link]
[Link]
[Link]

17 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

Select an option:
2
Enter Position to delete:
2

List Elements from Left to Right:


=>11=>33=>44
[Link]
[Link]
[Link]
[Link]

Select an option:
3

List Elements from Left to Right:


=>11=>33=>44
[Link]
[Link]
[Link]
[Link]

Select an option:
4

List Elements from Left to Right:


=>11=>33=>44

18 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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 the selected color. Initially, there is no message shown.

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Lights extends JFrame implements ItemListener
{
public JLabel l1, l2;
public JRadioButton r1, r2, r3;
public ButtonGroup bg;
public JPanel p, p1;
public Lights()
{
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("Comic Sans MS", [Link], 60);
[Link](f);
add(l1);
[Link](l1);
add(p);
l2 = new JLabel("Select Lights");
[Link](l2);
JRadioButton r1 = new JRadioButton("Red Light");
[Link]([Link]);
[Link](r1);
[Link](this);
JRadioButton r2 = new JRadioButton("Yellow Light");
[Link]([Link]);
[Link](r2);
[Link](this);
JRadioButton r3 = new JRadioButton("Green Light");
[Link]([Link]);
[Link](r3);
[Link](this);
add(p1);
bg = new ButtonGroup();
[Link](r1);
[Link](r2);
[Link](r3);
setVisible(true);
}
public void itemStateChanged(ItemEvent i)
{

19 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

JRadioButton jb = (JRadioButton) [Link]();


switch ([Link]())
{
case "Red Light":
[Link]("STOP");
[Link]([Link]);
break;
case "Yellow Light":
[Link]("READY");
[Link]([Link]);
break;
case "Green Light":
[Link]("GO");
[Link]([Link]);
break;
}
}
}
public class TrafficLights
{
public static void main(String[] args)
{
Lights l= new Lights( );
}
}

Output:

20 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

21 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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.

abstract class Shape


{
int x, y;
abstract void printArea();
}
class Rectangle extends Shape
{
void printArea()
{
[Link]("Area of Rectangle is " + x * y);
}
}
class Triangle extends Shape
{
public void printArea()
{
[Link]("Area of Triangle is " + (x * y) / 2);
}
}
class Circle extends Shape
{
public void printArea()
{
[Link]("Area of Circle is " + (22 * x * x) / 7);
}
}

class AbstractClass
{
public static void main(String[] args)
{
Rectangle r = new Rectangle();
r.x = 10;
r.y = 20;
[Link]();
Triangle t = new Triangle();
t.x = 30;
t.y = 35;
[Link]();
Circle c = new Circle();
c.x = 2;
[Link]();
}
}

22 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

Output:
Area of Rectangle is 200
Area of Triangle is 525
Area of Circle is 12

23 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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.

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Table extends JFrame
{
public Table()
{
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout g = new GridLayout(0, 3);
setLayout(g);
try
{
FileInputStream fis = new FileInputStream("D:\\Record25\\[Link]");
Scanner sc = new Scanner(fis).useDelimiter(",");
String[] arrayList;
String a;
while ([Link]())
{
a = [Link]();
arrayList = [Link](",");
for (String i : arrayList)
{
add(new JLabel(i));
}
}
}
catch(Exception ex) { }
setVisible(true);
}
}

public class TableGrid


{
public static void main(String[] args)
{
Table t = new Table();
}
}

24 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

Output:

Note: To execute the above program, create a file called “[Link]” and enter the following information in
it each value separated comma and each record (row) end by new line.

empno,ename,salary
1001,John,5000
1002,Raymond,4000
1003,Alice,2500

25 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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

import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
class Mouse extends JFrame implements MouseListener
{
JLabel l1;
public Mouse()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,400);
setLayout(new GridBagLayout());
l1 = new JLabel();
Font f = new Font("Comic Sans MS", [Link],22);
[Link](f);
[Link]([Link]);
[Link](Component.CENTER_ALIGNMENT);
[Link](Component.CENTER_ALIGNMENT);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent me)
{
[Link]("Mouse Exited");
}
public void mouseEntered(MouseEvent me)
{
[Link]("Mouse Entered");
}
public void mouseReleased(MouseEvent me)
{
[Link]("Mouse Released");
}
public void mousePressed(MouseEvent me)
{
[Link]("Mouse Pressed");
}
public void mouseClicked(MouseEvent me)
{
[Link]("Mouse Clicked");
}
}
public class MouseEvents
{
public static void main(String[] args)
{

26 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

Mouse m = new Mouse();


}
}

Output:

27 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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

import [Link].*;
import [Link].*;
public class HashTable
{
public static void main(String[] args)
{
try
{
FileInputStream fis = new FileInputStream("D:\\record25\\[Link]");
Scanner sc = new Scanner(fis).useDelimiter("\\t+");
Hashtable<String, String> ht = new Hashtable<String, String>();
String[] arrayList;
String a;
while ([Link]())
{
a = [Link]();
arrayList = [Link]("\\t+");
[Link](arrayList[0],arrayList[1]);
[Link](arrayList[0] + ":"+ arrayList[1]);
}
[Link]("[Link] by Name");
[Link]("[Link] by Mobile");
[Link]("[Link]");
int choice=1;
String name, mobile;
Scanner s = new Scanner([Link]);
while (choice>=1&&choice<3)
{
[Link]("Enter Your Choice 1/2/3: ");
choice=[Link]();
switch (choice)
{
case 1:
[Link]("Enter Name: ");
name = [Link]();
if ([Link](name))
{
[Link]("Mobile number is: " + [Link](name));
}
else
{
[Link]("Name Not Found");
}
break;
case 2:

28 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

[Link]("Enter Mobile Number: ");


mobile = [Link]();
if ([Link](mobile))
{
for ([Link] e : [Link]())
{
if ([Link]([Link]()))
{
[Link]("Name is: " + [Link]());
}
}
}
else
{
[Link]("Mobile Number Not Found");
}
break;
default:
[Link]("Choose Option betwen 1 and 3");
}
}
}
catch (Exception ex)
{
[Link]([Link]());
}
}
}

NOTE: Create a file named “[Link]” and enter the following details separated by tab
Airtel 9849012345
Idea 9848098480
Bsnl 9440012345

Output:
Air[Link]
Idea:9848098480
Bsnl:9440012345
[Link] by Name
[Link] by Mobile
[Link]
Enter Your Choice 1/2/3: 1
Enter Name: Airtel
Mobile number is: 9849012345
Enter Your Choice 1/2/3: 2
Enter Mobile Number: 9440012345
Name is: Bsnl
Enter Your Choice 1/2/3: 3
Choose Option betwen 1 and 3

29 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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

class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
[Link]("Interrupted Exception caught");
}
[Link]("Got:"+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
[Link]("Interrupted Exception caught");
}
this.n=n;
valueSet=true;
[Link]("Put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{

30 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

int i=0;
while(true)
{
[Link](i++);
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
[Link]();
}
}
}
class ProdCons
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
[Link]("Press Control-c to stop");
}
}

Output:
Got:26893
Put:26894
Got:26894
Put:26895
Got:26895
Put:26896
Got:26896
Put:26897
Got:26897
Put:26898
Got:26898
Put:26899
Got:26899
Put:26900
Got:26900

31 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

Put:26901
Got:26901
Put:26902
Got:26902
Put:26903
Got:26903
Put:26904
Got:26904
Put:26905
Got:26905
Put:26906
Got:26906
Put:26907
Got:26907
Put:26908
Got:26908
Put:26909
Got:26909
Put:26910
Got:26910
Put:26911
Got:26911
Put:26912
Got:26912
Put:26913
Got:26913
Ctrl+C

32 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

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

import [Link].*;
import [Link].*;
import [Link];
public class ListAllFiles
{
public void listFilesAndFolders(String directoryName)
{
File directory = new File(directoryName);
File[] fList = [Link](); //get all the files from a directory
for (File file : fList)
{
[Link]([Link]());
}
}
public void listFiles(String directoryName)
{
File directory = new File(directoryName);
File[] fList = [Link]();
for (File file : fList)
{
if ([Link]())
{
[Link]([Link]());
}
}
}
public void listFolders(String directoryName)
{
File directory = new File(directoryName);
File[] fList = [Link]();
for (File file : fList)
{
if ([Link]())
{
[Link]([Link]());
}
}
}
public void listFilesAndFilesSubDirectories(String directoryName)
{
File directory = new File(directoryName);
File[] fList = [Link]();
for (File file : fList)
{
if ([Link]())
{
[Link]([Link]());
}

33 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

else if ([Link]())
{
listFilesAndFilesSubDirectories([Link]());
}
}
}
public static void main(String[] args)
{
ListAllFiles laf = new ListAllFiles();
final String directoryWindows ="D://Record25";
[Link](directoryWindows);
}
}

Output:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]

34 | P a g e
CS307PC: OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB [Link]. II Year I Sem.

[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]

35 | P a g e

Common questions

Powered by AI

Swing provides a rich set of components for building graphical user interfaces in Java. In the context of developing the calculator program, Swing is used to organize components such as buttons, text fields, and layout managers like GridLayout and FlowLayout. These components and layouts allow the developer to create interactive and visually appealing user interfaces that handle actions and events seamlessly . The use of event listeners, particularly ActionListener, enables the program to respond to user interactions effectively, making it an ideal tool for applications requiring dynamic user input .

When simulating a traffic light system using radio buttons in Java, several design considerations are vital. Firstly, the interface should intuitively present red, yellow, and green options with corresponding actions that reflect real-world lights, such as 'Stop,' 'Ready,' and 'Go,' which should dynamically update in the UI. The choice of layout managers, such as GridLayout, should facilitate optimal organization of buttons and labels, ensuring a clear and accessible interface. Event handling via ItemListener ensures instantaneous response to selections, promoting a seamless user experience. Additionally, ensuring visual accessibility through color contrast and clear text indications furthers usability .

The Java program utilizes multithreading by creating separate threads to process integers differently based on their parity. A main thread generates random integers; if an integer is even, it spawns an Even thread to calculate and print the square of the number; if odd, an Odd thread computes and prints the cube of the number. This approach leverages parallel processing, allowing simultaneous computation of squares and cubes without waiting for the operations to complete sequentially. This not only optimizes performance in scenarios of complex computations but also efficiently uses system resources by delegating tasks to separate threads .

In concurrent programming, the primary challenges with shared data include race conditions, data inconsistency, and deadlocks due to incorrect synchronization among threads. In the Java programs provided, while threads like Even and Odd in the multithreading example work on independent tasks without shared data, these issues are mostly avoided. However, if shared resources were involved, proper synchronization techniques such as using synchronized blocks or methods would be necessary to ensure data integrity and avoid potential conflicts caused by concurrent modifications .

Adapter classes play a crucial role in managing complex Java interfaces by providing default implementations for all methods in the interface. When handling mouse events, for instance, instead of implementing MouseListener and providing empty methods for all events, an adapter class like MouseAdapter simplifies the code. Developers can override only the methods they need (e.g., mouseClicked, mousePressed), thus avoiding clutter and focusing on relevant actions. This increases code clarity and maintainability, significantly reducing the overhead of managing unused interface methods .

Object-oriented programming (OOP) in Java facilitates the refactoring process by promoting modularity and encapsulation, which makes it easier to manage, update, and extend code. In the prime number checking program, refactoring can be conducted by applying OOP principles, such as breaking down functionality into classes and methods. This separation of concerns allows individual components, like input handling, computation logic, and output, to be independently modified or improved without impacting other parts of the program. This modular design enhances code maintainability and reusability .

A doubly linked list offers several advantages over a singly linked list, particularly concerning node deletion and bidirectional traversal. In the shown implementation, the ability to navigate forwards and backwards with references to both next and previous nodes allows for more efficient insertion and deletion operations, as nodes can be easily accessed and removed from either end or from any position in constant time without needing to traverse the entire list from the start . This flexibility is particularly demonstrated in operations such as deleting a given element and displaying list contents after modification .

Exception handling in the integer division program is implemented using try-catch blocks to manage both input and arithmetic errors. The program attempts to parse the input from text fields as integers, catching a NumberFormatException if the input is not a valid number. It also checks for division by zero conditions, throwing and catching an ArithmeticException if the denominator is zero. Each exception, when caught, triggers a message dialog box that informs the user of the specific error, thereby ensuring the program can handle common input errors gracefully and informatively .

The Java applet for computing factorials utilizes event handling mechanisms to manage user input and output operations. When the 'Compute' button is clicked, the actionPerformed method, triggered by implementing ActionListener, reads the input number from a TextField, computes its factorial using a loop, and displays the result in another TextField . This use of event-driven programming in applets, although it does not directly involve threads, ensures operations occur in response to user actions, maintaining a responsive user interface.

The contact information program uses a Hashtable, a hashmap-like structure in Java, to store and retrieve key-value pairs efficiently. Each contact name and phone number are parsed from a text file and stored as entries in the Hashtable, allowing for quick retrieval and search operations. When a user inputs either a name or a phone number, the Hashtable is queried to find the corresponding value, demonstrating efficient O(1) average-time complexity for operations like insertions and lookups, leveraging the hashcode of the keys .

You might also like