KEMBAR78
Java Lab Manual | PDF | Area | Java (Programming Language)
0% found this document useful (0 votes)
30 views36 pages

Java Lab Manual

The document outlines the syllabus for the OOPS through Java Lab course at Sree Dattha Group of Institutions, detailing course objectives and outcomes focused on Java programming skills. It includes a list of experiments that cover various Java programming concepts such as GUI development, multithreading, and database connectivity. Additionally, it provides references for further reading and a mapping of experiments to course outcomes and program outcomes.

Uploaded by

mercy joyce
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)
30 views36 pages

Java Lab Manual

The document outlines the syllabus for the OOPS through Java Lab course at Sree Dattha Group of Institutions, detailing course objectives and outcomes focused on Java programming skills. It includes a list of experiments that cover various Java programming concepts such as GUI development, multithreading, and database connectivity. Additionally, it provides references for further reading and a mapping of experiments to course outcomes and program outcomes.

Uploaded by

mercy joyce
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
You are on page 1/ 36

SREE DATTHA GROUP OF INSTITUTIONS

(AUTONOMOUS)
B.Tech. in COMPUTER SCIENCE AND ENGINEERING
OOPS THROUGH JAVA LAB SYLLABUS (SDGI-R22 Regulations)

Course Code: CS307PC B.Tech II Year I Sem


L-T-P-S 0-0-3-0

No. of Credits: 1.5

Course Objectives:
● To write programs using abstract classes.
● To write programs for solving real world problems using the java collection framework.
● To write multithreaded programs.
● To write GUI programs using swing controls in Java.
● To introduce java compiler and eclipse platform.
● To impart hands-on experience with java programming.

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

Note:
1. UseLINUXandMySQLfortheLabExperiments.Thoughnotmandatory,encouragethe
use of the Eclipse platform.

2. The list suggests them inimum program set. Hence, the on cerned staff is
requested to add more problems to the list as needed.

List of Experiments:

1.Use Eclipse or Netbean platform and acquaint ourself with the various menus. Create
atestproject,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 smallprogramofabout10to15lineswhich contains atleast one ifelse
condition and a for loop.

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

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

B)Develop an applet in Java that receives an integer in one text field ,and computes its
factorial Value and returns it in another text field, when the button named“Compute”is clicked.
4. Write a Java program that creates a user interface to perform integer divisions. The user enters
two numbers in the text fields, Num1 and Num2.The division of Num1 and 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.

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.

6.Write a Java program for the following:

Create a doubly linked list of elements.


Delete a given element from the above list.
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 the selected color. Initially,
there is no message shown.

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

9. Suppose that a table named Table.txt is stored in a textfile.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.

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 inter thread communication.

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

14. Write a java program to connect a database by using JDBC.

15. Write a java program to store and retrieve data from database using JDBC..

REFERENCEBOOKS:

a. Java for Programmers,P.J.Deitel and H.M.Deitel,10th Edition Pearson education.

b. Thinking in Java,Bruce Eckel,Pearson Education.

c. Java Programming,D. S. Malikand P.S. Nair, Cengage Learning.

d. CoreJava,Volume1,9thedition, CayS.Horstmannand GCornell, Pearson.


List of Experiments Mapping with Cos,and POs

S.No Name Of the Experiment COs POs Mapping


mapping

Use Eclipse or Netbean platform and acquaint


ourself with the various menus. Create a
testproject,add a test class, and run it. See how
you can use auto suggestions, auto fill. Try code PO1,PO2,PO3,PO5,
1 formatter and code refactoring like renaming C217.1 PO6,PO7,PO9,PO10
variables, methods, and classes. Try debug step ,PO11,PO12
by step with a small program of about 10 to 15
lines which contains atleast one ifelse condition
and a for loop.

Write a Java program that works as a simple


calculator. Use a grid layout to arrange buttons PO1,PO2,PO3,PO5,
2 for the digits and for the +, -,*, % operations. Add C217.1 PO6,PO7,PO9,PO10
a text field to display the result. Handle any ,PO11,PO12
possible exceptions like divided by zero.

A) Develop an applet in Java that displays a simple


message.
PO1,PO2,PO3,PO5,
B)Develop an applet in Java that receives an
3 C217.5 PO6,PO7,PO9,PO10
integer in one text field ,and computes its factorial
,PO11,PO12
Value and returns it in another text field, when the
button named“Compute”is clicked.

Write a Java program that creates a user interface to


perform integer divisions. The user enters two
numbers in the text fields, Num1 and Num2.The
division of Num1 and Num2 is displayed in the
PO1,PO2,PO3,PO5,
Result field when the Divide button is clicked. If
4 C217.2 PO6,PO7,PO9,PO10
Num1 or Num2 were not an integer, the program
,PO11,PO12
would throw a Number Format Exception. If Num2
were Zero, the program would throw an Arithmetic
Exception. Display the exception in a message
dialog box.

Write a Java program that implements a multi-


thread application that has three threads. First
thread generates a random integer every 1 second PO1,PO2,PO3,PO5,
5 and if the value is even, the second thread C217.3 PO6,PO7,PO9,PO10
computes the square of the number and prints. If ,PO11,PO12
the value is odd, the third thread will print the
value of the cube of the number.
Write a Java program for the following:
PO1,PO2,PO3,PO4,
6 Create a doubly linked list of elements. C217.1 PO5,PO6,PO7,PO9,
Delete a given element from the above list. PO10,PO11,PO12
Display the contents of the list after deletion.

Write a Java program that simulates a traffic light.


The program lets the user select one of three
lights: red, yellow, or green with radio buttons. PO1,PO2,PO3,PO5,
7 On selecting a button, an appropriate message C217.2 PO6,PO7,PO9,PO10
with “Stop” or “Ready” or “Go” should appear ,PO11,PO12
above the buttons in the selected color. Initially,
there is no message shown.

Write a Java program to create an abstract class


named Shape that contains two integers and an
empty method named print Area ().Provide three
PO1,PO2,PO3,PO5,
classes named Rectangle, Triangle, and Circle
8 C217.3 PO6,PO7,PO9,PO10
such that each one of the classes extends the class
,PO11,PO12
Shape. Each one of the classes contains only the
method printArea () that prints the area of the
given shape.

Suppose that a table named Table.txt is stored in a


textfile.The first line in the file is the header, and
PO1,PO2,PO3,PO5,
the remaining lines correspond to rows in the
9 C217.2 PO6,PO7,PO9,PO10
table. The elements are separated by commas.
,PO11,PO12
Write a java program to display the table using
Labels in Grid Layout.

Write a Java program that handles all mouse


PO1,PO2,PO3,PO5,
events and shows the event name at the
10 C217.5 PO6,PO7,PO9,PO10
center of the window when a mouse event is
,PO11,PO12
fired(Use Adapter classes).

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 PO1,PO2,PO3,PO5,
11 a record are separated by a tab (\t). It takes a C217.4 PO6,PO7,PO9,PO10
name or phone number as input and prints the ,PO11,PO12
corresponding other value from the hash table
(hint: use hash tables).

Write a Java program that correctly implements PO1,PO2,PO3,PO5,


12 the producer – consumer problem using the C217.3 PO6,PO7,PO9,PO1
concept of inter thread communication. 0,PO11,PO12

Write a Java program to list all the files in a PO1,PO2,PO3,PO5,


13 directory including the files present in all its sub C217.4 PO6,PO7,PO9,PO10
directories. ,PO11,PO12
1.Use Eclipse or Net bean platform and acquaint ourselves 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 to15 lines which contains
atleast one ifelse condition and a for loop.

Aim: To create a test project, add a test class, and run it using Eclipse platform and acquaint
ourselves with the various menus. Observe how we can use auto suggestions, auto fill.

Procedure:

1. Set Up Eclipse
 Download and install Eclipse IDE for Java Developers.
 Launch Eclipse and choose a workspace (any folder).
2. Explore the Menus
Familiarize yourself with these menus:
 File: New projects, classes, files
 Edit: Refactor, format code, etc.
 Source: Generate getters/setters, format, organize imports
 Run: Run/debug your program
 Window: Open different views like Console, Outline
 Help: Eclipse documentation and updates
3. Create a Test Project and Class
1. Go to File → New → Java Project → Name it: TestProject
2. Right-click src folder → New → Class
3. Name it TestProgram and check the box for public static void main(String[] args).

4. Program (10–15 lines)

public class TestProgram


{
public static void main(String[] args)
{
int[] numbers = {2, 5, 7, 10, 15};
for (int num : numbers)
{
if (num % 2 == 0)
{
System.out.println(num + " is even");
}
else
{
System.out.println(num + " is odd");
}
}
}
}

5. Use Auto Suggestions & Auto Fill


 Start typing System.o... and press Ctrl + Space to auto-complete System.out.println.
 Eclipse suggests method names, variable names, etc.
6. Use Code Formatter
 Press Ctrl + Shift + F to auto-format the code.
 It aligns and indents the code properly.

7. Refactor Code

 Right-click on a variable (e.g., num) → Refactor → Rename → Change to number


 Same for class names, methods, etc.

8. Run the Program


 Click the green Run button (▶️ on toolbar), or press Ctrl + F11
 See output in Console tab.
9. Debug the Program
1. Set breakpoints:
o Double-click the left margin next to if (num % 2 == 0) line.
2. Right-click the file → Debug As → Java Application.
3. Use the Debug Perspective:
o Step Over: F6
o Step Into: F5
o Resume: F8
o Watch variable values in the Variables view.
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.

Aim: To create a simple calculator using grid layout to arrange buttons for the digits and
for the +, -,*, % operations.

Program:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CalculatorApp extends JFrame
{
private JTextField inputField;
private JButton[] numberButtons;
private JButton addButton, subtractButton, multiplyButton, divideButton, equalButton, clearButton;
private double firstNum, secondNum, result;
private char operator;
public CalculatorApp()
{
initializeUI();
initializeButtons();
addComponentsToFrame();
attachButtonListeners();
}
private void initializeUI()
{
setTitle("Simple Calculator");
setSize(300, 400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(5, 4));
}
private void initializeButtons()
{
inputField = new JTextField();
inputField.setEditable(false);
inputField.setHorizontalAlignment(SwingConstants.RIGHT);
numberButtons = new JButton[10];
for (int i = 0; i < 10; i++)
{
numberButtons[i] = new JButton(String.valueOf(i));
}
addButton = new JButton("+");
subtractButton = new JButton("-");
multiplyButton = new JButton("*");
divideButton = new JButton("/");
equalButton = new JButton("=");
clearButton = new JButton("C");
}
private void addComponentsToFrame()
{
add(inputField);
for (int i = 1; i < 10; i++)
{
add(numberButtons[i]);
}
add(numberButtons[0]);
add(addButton);
add(subtractButton);
add(multiplyButton);
add(divideButton);
add(equalButton);
add(clearButton);
}
private void attachButtonListeners()
{
for (int i = 0; i < 10; i++)
{
int num = i;
numberButtons[i].addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
inputField.setText(inputField.getText() + num);
}
});
}
addButton.addActionListener(e -> setOperator('+'));
subtractButton.addActionListener(e -> setOperator('-'));
multiplyButton.addActionListener(e -> setOperator('*'));
divideButton.addActionListener(e -> setOperator('/'));
equalButton.addActionListener(e -> calculateResult());
clearButton.addActionListener(e ->
{
inputField.setText("");
firstNum = secondNum = result = 0;
operator = '\0';
});
}

private void setOperator(char op) {


firstNum = Double.parseDouble(inputField.getText());
inputField.setText("");
operator = op;
}

private void calculateResult()


{
secondNum = Double.parseDouble(inputField.getText());
try
{
switch (operator)
{
case '+':
result = firstNum + secondNum;
break;
case '-':
result = firstNum - secondNum;
break;
case '*':
result = firstNum * secondNum;
break;
case '/':
if (secondNum == 0)
{
throw new ArithmeticException("Division by zero is not allowed.");
}
result = firstNum / secondNum;
break;
default:
throw new IllegalArgumentException("Invalid operator");
}
inputField.setText(String.valueOf(result));
}
catch (NumberFormatException ex)
{
inputField.setText("Error");
}
catch (ArithmeticException ex)
{
inputField.setText("Error: " + ex.getMessage());
}
catch (IllegalArgumentException ex)
{
inputField.setText("Error: " + ex.getMessage());
}
}
public static void main(String[] args)
{
CalculatorApp calculator = new CalculatorApp();
calculator.setVisible(true);

}
}

Output:
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.

Aim: To Develop an applet in Java that displays a simple message .


Program:

import java. awt.*;


import java. applet.*;
/*<applet code="FirstApplet" width=400 height=300></applet>*/
public class FirstApplet extends Applet {
public void paint(Graphics g) {
g.setColor(Color.blue);
Font font = new Font("Arial", Font.BOLD, 16);
g.setFont(font);
g.drawString("This is My First Applet",60,110);
}
}
Output:

b)AIM:Develop an applet in Java that receives an integer in one textfield,and computes its factorial
value and returns it in another textfield,when the button named“Compute”is clicked.
Program:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="FactorialApplet" width=500 height=250>
</applet>*/
public class FactorialApplet extends Applet implements ActionListener
{
Label L1,L2;
TextField T1,T2;
Button B1;
public void init()
{
L1=new Label("Enter any Number : ");
add(L1);
T1=new TextField(10);
add(T1);
L2=new Label("Factorial of Num : ");
add(L2);
T2=new TextField(10);
add(T2);
B1=new Button("Compute");
add(B1);
B1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==B1)
{
int value=Integer.parseInt(T1.getText());
int fact=factorial(value);
T2.setText(String.valueOf(fact));
}
}
int factorial(int n)
{
if(n==0)
return 1;
else
return n*factorial(n-1);
}
}
Output:
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 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.

Aim: To Develop a Java program that creates a user interface to perform integer divisions.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class IntegerDivisionApp extends JFrame


{
private JTextField num1Field;
private JTextField num2Field;
private JTextField resultField;
private JButton divideButton;
public IntegerDivisionApp()
{
initializeUI();
addComponentsToFrame();
attachButtonListener();
}
private void initializeUI() {
setTitle("Integer Division Calculator");
setSize(300, 200);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2));
}
private void addComponentsToFrame()
{
JLabel num1Label = new JLabel("Num1:");
num1Field = new JTextField();

JLabel num2Label = new JLabel("Num2:");


num2Field = new JTextField();
JLabel resultLabel = new JLabel("Result:");
resultField = new JTextField();
resultField.setEditable(false);
divideButton = new JButton("Divide");
add(num1Label);
add(num1Field);
add(num2Label);
add(num2Field);
add(resultLabel);
add(resultField);
add(new JLabel()); // Empty label for formatting
add(divideButton);
}
private void attachButtonListener()
{
divideButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try
{
int num1 = Integer.parseInt(num1Field.getText());
int num2 = Integer.parseInt(num2Field.getText());
if (num2 == 0)
{
throw new ArithmeticException("Cannot divide by zero!");
}
int result = num1 / num2;
resultField.setText(String.valueOf(result));
}
catch (NumberFormatException ex)
{
showMessageDialog("Error: Please enter valid integers for Num1 and Num2.");
}
catch (ArithmeticException ex)
{
showMessageDialog("Error: " + ex.getMessage());
}
}
});
}
private void showMessageDialog(String message)
{
JOptionPane.showMessageDialog(this, message, "Error", JOptionPane.ERROR_MESSAGE);
}
public static void main(String[] args)
{
IntegerDivisionApp app = new IntegerDivisionApp();
app.setVisible(true);
}
}

Output:
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.

Aim: To Develop a Java program that implements a multi-thread application that has three
threads
Program:
import java.util.*;
// class for Even Number
class EvenNum implements Runnable
{
public int a;
public EvenNum(int a)
{
this.a = a;
}
public void run()
{
System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " + a * a);
}
} // class for Odd Number
class OddNum implements Runnable
{
public int a;
public OddNum(int a)
{
this.a = a;
}
public void run()
{
System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a * a* a);
}
}
// class to generate random number
class RandomNumGenerator extends Thread
{
public void run()
{
int n = 0;
Random rand = new Random();
try
{
for (int i = 0; i < 10; i++)
{
n = rand.nextInt(20);
System.out.println("Generated Number is " + n);
// check if random number is even or odd
if (n % 2 == 0)
{
Thread thread1 = new Thread(new EvenNum(n));
thread1.start();
}
else
{
Thread thread2 = new Thread(new OddNum(n));
thread2.start();
}
// thread wait for 1 second
Thread.sleep(1000);
System.out.println("------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
// Driver class
public class MultiThreadRandOddEven
{
public static void main(String[] args)
{
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}

Output:
6. Write a Java program for the following:

Create a doubly linked list of elements.


Delete a given element from the above list.
Display the contents of the list after deletion.

Aim:To Develop a java program to create a doubly linked list of elements and delete a
given elements from the above list and display the contents of the lis
Program:
import java.util.*;
public class DoublyLinkListDemo
{
public static void main(String[] args)
{
int i,ch,element,position;
LinkedList<Integer> dblList = new LinkedList<Integer>();
System.out.println("1.Insert element at begining");
System.out.println("2.Insert element at end");
System.out.println("3.Insert element at position");
System.out.println("4.Delete a given element");
System.out.println("5.Display elements in the list");
System.out.println("6.Exit");
Scanner sc=new Scanner(System.in);
Do

{
System.out.print("Choose your choice(1 - 6) :");
ch=sc.nextInt();
switch(ch)

{
case 1: // To read element form the user
System.out.print("Enter an element to insert at begining : ");
element=sc.nextInt();
// to add element to doubly linked list at begining
dblList.addFirst(element);
System.out.println("Successfully Inserted");
break;
case 2: // To read element form the user
System.out.print("Enter an element to insert at end : ");
element=sc.nextInt();
// to add element to doubly linked list at end
dblList.addLast(element);
System.out.println("Successfully Inserted");
break;
case 3: // To read position form the user
System.out.print("Enter position to insert element : ");
position=sc.nextInt();
// checks if the position is lessthan or equal to list size.
if(position<=dblList.size())
{
// To read element
System.out.print("Enter element : ");
element=sc.nextInt();
// to add element to doubly linked list at given position
dblList.add(position,element);
System.out.println("Successfully Inserted");
}
else
{
System.out.println("Enter the size between 0 to"+dblList.size());
}
break;
case 4: // To read element form the user to remove
System.out.print("Enter element to remove : ");
Integer ele_rm;
ele_rm=sc.nextInt();
if (dblList.contains(ele_rm))
{
dblList.remove(ele_rm);
System.out.println("Successfully Deleted");
Iterator itr=dblList.iterator();
System.out.println("Elements after deleting :"+ele_rm);
while(itr.hasNext())
{
System.out.print(itr.next()+"<->");
}
System.out.println("NULL");
}
else
{
System.out.println("Element not found");
}
break;

case 5: // To Display elements in the list


Iterator itr=dblList.iterator();
System.out.println("Elements in the list :");
while(itr.hasNext())
{
System.out.print(itr.next()+"<->");
}
System.out.println("NULL");
break;

case 6: System.out.println("Program terminated");


break;
default:System.out.println("Invalid choice");
}
}
while(ch!=6);
}
}
Output:
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
Aim:To Develop a Java program that simulates a traffic light
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TrafficLightSimulator1 extends JFrame implements ActionListener {
private JRadioButton redButton, yellowButton, greenButton;
private JLabel messageLabel;
private ButtonGroup group;
public TrafficLightSimulator1()
{
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Message label (initially empty)
messageLabel = new JLabel("", SwingConstants.CENTER);
messageLabel.setFont(new Font("Arial", Font.BOLD, 20));
add(messageLabel, BorderLayout.NORTH);
// Radio buttons
redButton = new JRadioButton("Red");
yellowButton = new JRadioButton("Yellow");
greenButton = new JRadioButton("Green");
// Group buttons
group = new ButtonGroup();
group.add(redButton);
group.add(yellowButton);
group.add(greenButton);
// Add action listeners
redButton.addActionListener(this);
yellowButton.addActionListener(this);
greenButton.addActionListener(this);
// Panel for radio buttons
JPanel buttonPanel = new JPanel();
buttonPanel.add(redButton);
buttonPanel.add(yellowButton);
buttonPanel.add(greenButton);
add(buttonPanel, BorderLayout.CENTER);
}
@Override
public void actionPerformed(ActionEvent e)
{
if (redButton.isSelected())
{
messageLabel.setText("Stop");
messageLabel.setForeground(Color.RED);
}
else if (yellowButton.isSelected())
{
messageLabel.setText("Ready");
messageLabel.setForeground(Color.ORANGE);
}
else if (greenButton.isSelected())
{
messageLabel.setText("Go");
messageLabel.setForeground(Color.GREEN.darker());
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(() ->
{
new TrafficLightSimulator1().setVisible(true);
});
}
}
Output:
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 printArea () that prints the area of the given shape.

Aim: To develop Java program to create an abstract class named Shape that contains
two integers and an empty method named print Area ().
Program:
import java.util.*;
abstract class Shape
{
public int x,y;
public abstract void printArea();
}
class Rectangle1 extends Shape
{
public void printArea()
{
float area;
area= x * y;
System.out.println("Area of Rectangle is " +area);
}
}
class Triangle extends Shape
{
public void printArea()
{
float area;
area= (x * y) / 2.0f;
System.out.println("Area of Triangle is " + area);
}
}
class Circle extends Shape
{
public void printArea()
{
float area;
area=(22 * x * x) / 7.0f;
System.out.println("Area of Circle is " + area);
}
}
public class AreaOfShapes
{
public static void main(String[] args)
{
int choice;
Scanner sc=new Scanner(System.in);
System.out.println("Menu \n 1.Area of Rectangle \n 2.Area of Traingle \n 3.Area
of Circle ");
System.out.print("Enter your choice : ");
choice=sc.nextInt();
switch(choice) {
case 1: System.out.println("Enter length and breadth for area of rectangle : ");
Rectangle1 r = new Rectangle1();
r.x=sc.nextInt();
r.y=sc.nextInt();
r.printArea();
break;
case 2: System.out.println("Enter bredth and height for area of traingle : ");
Triangle t = new Triangle();
t.x=sc.nextInt();
t.y=sc.nextInt();
t.printArea();
break;
case 3: System.out.println("Enter radius for area of circle : ");
Circle c = new Circle();
c.x = sc.nextInt();
c.printArea();
break;
default:System.out.println("Enter correct choice");
}
}
}
Output:
9. Suppose that a table named Table.txt is stored in a text file. The first line in the file is the
header, and the remaining lines correspond to rows in the table. The elements are
separated by commas. Write a java program to display the table using Labels in Grid
Layout.

Aim: To Develop A java program to display the table using Labels in Grid
LayoutSupposethatatablenamedTable.txtisstoredinatextfile.Thefirstlineinthefileisthehe
ader,and the remaining lines correspond to rows in the table. The elements are
separated by commas
Program:
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class Text_To_Table extends JFrame
{
public void convertTexttotable()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400,300);
GridLayout g = new GridLayout(0, 4);
setLayout(g);
try
{
FileInputStream fis = new FileInputStream("table.txt");
Scanner sc = new Scanner(fis);
String[] arrayList;
String str;
while (sc.hasNextLine())
{
str = sc.nextLine();
arrayList = str.split(",");
for (String i : arrayList)
{
add(new Label(i));
}
}
}
catch (Exception ex) {
ex.printStackTrace();
}
setVisible(true);
setTitle("Display Data in Table");
}
}
public class TableText
{
public static void main(String[] args)
{
Text_To_Table tt = new Text_To_Table();
tt.convertTexttotable();
}
}

Text file:
Name,Age,Gender
Alice,22,Female
Bob,25,Male
Carol,23,Female

Output:
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: To Develop 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).
Program:
import javax.swing.*;
import java.awt.*;
import javax.swing.event.*;
import java.awt.event.*;
class MouseEventPerformer extends JFrame implements MouseListener
{
JLabel l1;
public MouseEventPerformer()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300,300);
setLayout(new FlowLayout(FlowLayout.CENTER));
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
l1.setFont(f);
l1.setForeground(Color.BLUE);
add(l1);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
l1.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
l1.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
l1.setText("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
l1.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
l1.setText("Mouse Clicked");
}
public static void main(String[] args) {
MouseEventPerformer mep = new MouseEventPerformer();
}
}
Output:
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: To develop a Java program that loads names and phone numbers from a text file ,it
takes a name or phone number as input and prints the corresponding other value from the
hash table.
Program:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class PhoneBookApp
{
private static final String FILE_NAME = "data1.txt";
private static final String DELIMITER = "\t";
private static Map<String, String> phoneBook = new HashMap<>();
public static void main(String[] args)
{
loadContactsFromFile();
searchContact();
}
private static void loadContactsFromFile()
{
try (BufferedReader reader = new BufferedReader(new FileReader("data1.txt"))) {
String line;
while ((line = reader.readLine()) != null)
{
String[] parts = line.split(DELIMITER);
if (parts.length == 2)
{
String name = parts[0].trim();
String phoneNumber = parts[1].trim();
phoneBook.put(name, phoneNumber);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}

private static void searchContact()


{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a name or phone number to search: ");
String searchTerm = scanner.nextLine().trim();
String result = phoneBook.get(searchTerm);
if (result != null)
{
if (phoneBook.containsKey(searchTerm))
{
System.out.println("Name: " + searchTerm + ", Phone Number: " + result);
}
else
{
for (Map.Entry<String, String> entry : phoneBook.entrySet())
{
if (entry.getValue().equals(searchTerm))
{
System.out.println("Name:"+entry.getKey()+",Phone umber: " + searchTerm);
return;
}
}
}
}
else
{
System.out.println("Contact not found!");
}
}
}
data1.txt
Alice 9876543210
Bob 9123456789
Charlie 8000123456
Output:
12. Write a Java program that correctly implements the producer – consumer
problem using the concept of inter thread communication
Aim: To develop a Java program that correctly implements the producer – consumer
problem using the concept of inter thread communication.
Program:
import java.util.LinkedList;
import java.util.Queue;

class Buffer {
private final int maxSize;
private final Queue<Integer> buffer;

public Buffer(int maxSize)


{
this.maxSize = maxSize;
this.buffer = new LinkedList<>();
}

public synchronized void produce(int value) throws InterruptedException


{
while (buffer.size() >= maxSize)
{
wait(); // Buffer is full, wait for consumer to consume data
}

buffer.offer(value);
System.out.println("Produced: " + value);
notify(); // Notify consumer that data is available
}

public synchronized int consume() throws InterruptedException


{
while (buffer.isEmpty())
{
wait(); // Buffer is empty, wait for producer to produce data
}

int value = buffer.poll();


System.out.println("Consumed: " + value);
notify(); // Notify producer that space is available in the buffer
return value;
}
}

class Producer extends Thread


{
private final Buffer buffer;

public Producer(Buffer buffer)


{
this.buffer = buffer;
}

@Override
public void run()
{
try
{
for (int i = 1; i <= 5; i++)
{
buffer.produce(i);
Thread.sleep(1000);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

class Consumer extends Thread


{
private final Buffer buffer;

public Consumer(Buffer buffer)


{
this.buffer = buffer;
}

@Override
public void run()
{
try
{
for (int i = 0; i < 5; i++)
{
buffer.consume();
Thread.sleep(1500);
}
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public class ProducerConsumerApp
{
public static void main(String[] args)
{
Buffer buffer = new Buffer(3);
Producer producer = new Producer(buffer);
Consumer consumer = new Consumer(buffer);
producer.start();
consumer.start();
try
{
producer.join();
consumer.join();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

Output:
13. Write a Java program to list all the files in a directory including the files
present in all its sub directories

Aim: To develop a Java program to list all the files in a directory including the files
present in all its sub directories.

Program:
import java.io.File;
public class ListAllFiles
{
public static void main(String[] args)
{
// You can replace this with a dynamic input if needed
String directoryPath = "C:\\PRASHANTHI"; // Change this path

File rootDir = new File(directoryPath);

if (rootDir.exists() && rootDir.isDirectory())


{
listFilesRecursively(rootDir);
}
else
{
System.out.println("Invalid directory path.");
}
}
public static void listFilesRecursively(File dir)
{
File[] filesAndDirs = dir.listFiles();
if (filesAndDirs != null)
{
for (File file : filesAndDirs)
{
if (file.isFile())
{
System.out.println("File: " + file.getAbsolutePath());
}
else if (file.isDirectory())
{
System.out.println("Directory: " + file.getAbsolutePath());
listFilesRecursively(file); // Recursive call for subdirectory
}
}
}
}
}
Output:

You might also like