0% found this document useful (0 votes)
72 views27 pages

Java Programs for GUI and Data Structures

Uploaded by

jjahnavi013
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)
72 views27 pages

Java Programs for GUI and Data Structures

Uploaded by

jjahnavi013
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

Java LAB Manual

[Link] 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.
Program:
public class NumberCheck {
public static void main(String[] args) {
int totalEven = 0;
int totalodd = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
[Link](i + " is even");
totalEven++;
} else {
[Link](i + " is odd");
totalodd++;
}
}
[Link]("Total even numbers from 1 to 10: " + totalEven);
[Link]("Total even numbers from 1 to 10: " + totalodd);
}}
Output:

[Link] 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.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
public class SimpleCalculator extends JFrame implements ActionListener {
JTextField textField;
double num1 = 0, num2 = 0, result = 0;
String operator = "";
public SimpleCalculator() {
setTitle("Simple Calculator");
setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new BorderLayout());
textField = new JTextField();
[Link](false);
add(textField, [Link]);
JPanel panel = new JPanel();
[Link](new GridLayout(4, 4, 5, 5));
String[] buttons = {
"7", "8", "9", "+",
"4", "5", "6", "-",
"1", "2", "3", "*",
"0", "C", "=", "%"
};
for (String text : buttons) {
JButton button = new JButton(text);
[Link](this);
[Link](button);
}
add(panel, [Link]);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String input = [Link]();
if ([Link](0) >= '0' && [Link](0) <= '9') {
[Link]([Link]() + input);
} else if ([Link]("C")) {
[Link]("");
num1 = num2 = result = 0;
operator = "";
} else if ([Link]("=")) {
try {
num2 = [Link]([Link]());
switch (operator) {
case "+": result = num1 + num2; break;
case "-": result = num1 - num2; break;
case "*": result = num1 * num2; break;
case "%":
if (num2 == 0) throw new ArithmeticException();
result = num1 % num2; break;
}
[Link]([Link](result));
} catch (ArithmeticException ex) {
[Link]("Cannot divide by 0");
}
} else {
try {
num1 = [Link]([Link]());
operator = input;
[Link]("");
} catch (NumberFormatException ex) {
[Link]("Invalid Input");
}
}
}
public static void main(String[] args) {
new SimpleCalculator();
}
}

Output:

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


Program:
import [Link].*;
public class SimpleMessageSwing {
public static void main(String[] args) {
JFrame frame = new JFrame("Simple Message");
[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);
JLabel messageLabel = new JLabel("Hello, Java Swing!", [Link]);
[Link](messageLabel);

[Link](true);
}}
Output:

3.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.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
public class FactorialSwingApp extends JFrame implements ActionListener {
JTextField inputField, outputField;
JButton computeBtn;
public FactorialSwingApp() {
setTitle("Factorial Calculator");
setSize(300, 200);
setLayout(new FlowLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
JLabel inputLabel = new JLabel("Enter Number:");
inputField = new JTextField(10);
JLabel outputLabel = new JLabel("Factorial:");
outputField = new JTextField(15);
[Link](false);
computeBtn = new JButton("Compute");
[Link](this);
add(inputLabel);
add(inputField);
add(outputLabel);
add(outputField);
add(computeBtn);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
int num = [Link]([Link]());
long fact = 1;
for (int i = 1; i <= num; i++) {
fact *= i;
}
[Link]([Link](fact));
} catch (NumberFormatException ex) {
[Link]("Invalid Input");
}
}
public static void main(String[] args) {
new FactorialSwingApp();
}
}
Output:

[Link] 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.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
public class DivisionGUI extends JFrame implements ActionListener {
JTextField num1Field, num2Field, resultField;
JButton divideButton;
public DivisionGUI() {
setTitle("Integer Division");
setSize(350, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(4, 2, 10, 10));
// Labels and TextFields
add(new JLabel("Num1:"));
num1Field = new JTextField();
add(num1Field);
add(new JLabel("Num2:"));
num2Field = new JTextField();
add(num2Field);
add(new JLabel("Result:"));
resultField = new JTextField();
[Link](false);
add(resultField);
// Button
divideButton = new JButton("Divide");
[Link](this);
add(divideButton);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try {
int num1 = [Link]([Link]().trim());
int num2 = [Link]([Link]().trim());
if (num2 == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
int result = num1 / num2;
[Link]([Link](result));
} catch (NumberFormatException ex) {
[Link](this, "Please enter valid integers.", "Number
Format Error", JOptionPane.ERROR_MESSAGE);
} catch (ArithmeticException ex) {
[Link](this, "Division by zero is not allowed.",
"Arithmetic Error", JOptionPane.ERROR_MESSAGE);
}
}
public static void main(String[] args) {
new DivisionGUI();
}
}
Output:

[Link] 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.
Programs:
import [Link];
class NumberGenerator extends Thread {
public void run() {
Random rand = new Random();
while (true) {
int num = [Link](100); // Random number between 0–99
[Link]("\nGenerated Number: " + num);
if (num % 2 == 0) {
new SquareThread(num).start();
} else {
new CubeThread(num).start();
}
try {
[Link](1000); // Wait for 1 second
} catch (InterruptedException e) {
[Link]("Interrupted: " + e);
}
}
}
}
class SquareThread extends Thread {
int number;
SquareThread(int num) {
[Link] = num;
}
public void run() {
int square = number * number;
[Link]("Square of " + number + " is: " + square);
}
}
class CubeThread extends Thread {
int number;
CubeThread(int num) {
[Link] = num;
}
public void run() {
int cube = number * number * number;
[Link]("Cube of " + number + " is: " + cube);
}
}
public class MultiThreadExample {
public static void main(String[] args) {
NumberGenerator ng = new NumberGenerator();
[Link](); // Start the generator thread
}
}

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.
Program:
import [Link].*;
class Node {
int data;
Node prev, next;
Node(int data) {
[Link] = data;
}
}
class DoublyLinkedList {
Node head;
void insert(int data) {
Node newNode = new Node(data);
if (head == null) head = newNode;
else {
Node temp = head;
while ([Link] != null) temp = [Link];
[Link] = newNode;
[Link] = temp;
}
}
void delete(int val) {
Node temp = head;
while (temp != null && [Link] != val) temp = [Link];

if (temp == null) {
[Link]("Element not found.");
return;
}
if (temp == head) head = [Link];
if ([Link] != null) [Link] = [Link];
if ([Link] != null) [Link] = [Link];
[Link]("Deleted: " + val);
}
void display() {
[Link]("List: ");
for (Node temp = head; temp != null; temp = [Link])
[Link]([Link] + " ");
[Link]();
}
}
public class DLLDemo {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
DoublyLinkedList dll = new DoublyLinkedList();
[Link]("How many elements? ");
int n = [Link]();
[Link]("Enter elements:");
while (n-- > 0) [Link]([Link]());
[Link]();
[Link]("Delete element: ");
[Link]([Link]());
[Link]();
[Link]();
}
}
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.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
public class TrafficLightSimulator extends JFrame implements ActionListener {
JRadioButton redBtn, yellowBtn, greenBtn;
JLabel messageLabel;
public TrafficLightSimulator() {
setTitle("Traffic Light Simulator");
setSize(300, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
// Label (initially empty)
messageLabel = new JLabel("");
[Link](new Font("Arial", [Link], 24));
add(messageLabel);
// Radio Buttons
redBtn = new JRadioButton("Red");
yellowBtn = new JRadioButton("Yellow");
greenBtn = new JRadioButton("Green");
// Grouping radio buttons
ButtonGroup group = new ButtonGroup();
[Link](redBtn);
[Link](yellowBtn);
[Link](greenBtn);
// Add Action Listeners
[Link](this);
[Link](this);
[Link](this);
// Add buttons to frame
add(redBtn);
add(yellowBtn);
add(greenBtn);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if ([Link]()) {
[Link]("Stop");
[Link]([Link]);
} else if ([Link]()) {
[Link]("Ready");
[Link]([Link]);
} else if ([Link]()) {
[Link]("Go");
[Link]([Link]);
}
}
public static void main(String[] args) {
new TrafficLightSimulator();
}
}
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 print Area () that prints the area of the given shape.
Program:
import [Link];
abstract class Shape {
int a, b;
abstract void printArea();
}
class Rectangle extends Shape {
Rectangle(int len, int bre) { a = len; this.b = bre; }
void printArea() { [Link]("Rectangle: " + (a * b)); }
}
class Triangle extends Shape {
Triangle(int base, int height) { a = base; b = height; }
void printArea() { [Link]("Triangle: " + (0.5 * a * b)); }
}
class Circle extends Shape {
Circle(int r) { a = r; }
void printArea() { [Link]("Circle: " + ([Link] * a * a)); }
}
public class ShapeTest {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Rectangle length bredth: ");
new Rectangle([Link](), [Link]()).printArea();
[Link]("Triangle base height: ");
new Triangle([Link](), [Link]()).printArea();
[Link]("Circle radius: ");
new Circle([Link]()).printArea();
[Link]();
}
}
Output:

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.
Program:
import [Link].*;
import [Link].*;
import [Link].*;
public class TableDisplay extends JFrame {
public TableDisplay() {
setTitle("Table Viewer");
setSize(400, 200);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(0, 3)); // 3 columns (based on [Link])
try {
BufferedReader br = new BufferedReader(new FileReader("[Link]"));
String line;
while ((line = [Link]()) != null) {
String[] fields = [Link](",");
for (String field : fields) {
add(new JLabel([Link](), [Link]));
}
}
[Link]();
} catch (IOException e) {
add(new JLabel("Error: File not found", [Link]));
}
setVisible(true);
}
public static void main(String[] args) {
new TableDisplay();
}
}
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).
Program:
import [Link].*;
import [Link].*;
import [Link].*;
public class MouseEventsDemo extends JFrame {
String msg = "";
public MouseEventsDemo() {
setTitle("Mouse Event Demo");
setSize(400, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
msg = "Mouse Clicked";
repaint();
}
public void mousePressed(MouseEvent e) {
msg = "Mouse Pressed";
repaint();
}
public void mouseReleased(MouseEvent e) {
msg = "Mouse Released";
repaint();
}
public void mouseEntered(MouseEvent e) {
msg = "Mouse Entered";
repaint();
}
public void mouseExited(MouseEvent e) {
msg = "Mouse Exited";
repaint();
}
});
setVisible(true);
}
public void paint(Graphics g) {
[Link](g);
[Link](new Font("Arial", [Link], 20));
[Link](msg, getWidth() / 2 - 60, getHeight() / 2);
}
public static void main(String[] args) {
new MouseEventsDemo();
}
}
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).
Program:
import [Link].*;
import [Link].*;
public class PhoneBookSimple {
public static void main(String[] args) {
HashMap<String, String> phoneBook = new HashMap<>();
try (BufferedReader br = new BufferedReader(new
FileReader("[Link]"))) {
String line;
while ((line = [Link]()) != null) {
String[] parts = [Link]("\t");
if ([Link] == 2) {
[Link](parts[0].trim(), parts[1].trim()); // Name → Phone
[Link](parts[1].trim(), parts[0].trim()); // Phone → Name
}
}
} catch (IOException e) {
[Link]("File error: " + e);
return;
}
Scanner sc = new Scanner([Link]);
[Link]("Enter Name or Phone: ");
String input = [Link]().trim();

if ([Link](input)) {
[Link]("Result: " + [Link](input));
} else {
[Link]("Record not found.");
}
[Link]();
}
}

Output:

12. Write a Java program that correctly implements the producer – consumer problem using the
concept of inter thread communication.
Program:
class Buffer {
int data;
boolean hasData = false;
synchronized void produce(int val) {
while (hasData) {
try { wait(); } catch (Exception e) {}
}
data = val;
[Link]("Produced: " + data);
hasData = true;
notify();
}
synchronized void consume() {
while (!hasData) {
try { wait(); } catch (Exception e) {}
}
[Link]("Consumed: " + data);
hasData = false;
notify();
}
}
class Producer extends Thread {
Buffer b;
Producer(Buffer b) { this.b = b; }
public void run() {
for (int i = 1; i <= 5; i++) {
[Link](i);
try { [Link](500); } catch (Exception e) {}
}
}
}
class Consumer extends Thread {
Buffer b;
Consumer(Buffer b) { this.b = b; }
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]();
try { [Link](500); } catch (Exception e) {}
}
}
}
public class PC {
public static void main(String[] args) {
Buffer b = new Buffer();
new Producer(b).start();
new Consumer(b).start();
}
}
Output:

13. Write a Java program to list all the files in a directory including the files present in all its
subdirectories.
Program:
import [Link];
public class ListFilesRecursively {
public static void main(String[] args) {
File folder = new File("your file path"); // replace with your directory path
if ([Link]() && [Link]()) {
listFiles(folder);
} else {
[Link]("Invalid directory!");
}
}
static void listFiles(File dir) {
File[] files = [Link]();
if (files == null) return;
for (File file : files) {
if ([Link]()) {
[Link]("File: " + [Link]());
} else if ([Link]()) {
[Link]("Directory: " + [Link]());
listFiles(file); // Recursive call
}
}
}
}
Output:

Common questions

Powered by AI

Java's exception handling mechanisms enhance user experience by providing robust error management and user feedback. In GUI applications like division and calculator programs, exceptions such as ArithmeticException and NumberFormatException are caught to prevent application crashes and improve reliability . This involves displaying user-friendly error messages through dialog boxes or GUI components to guide users, such as preventing division by zero or handling invalid inputs without interrupting the user workflow. Effective use of exception handling promotes resilience against erroneous user actions and unanticipated runtime conditions.

One potential issue is handling division by zero, which can cause a runtime exception in Java. To address this, the code explicitly throws and catches an ArithmeticException, displaying an appropriate error message to the user . Another issue is ensuring valid format input for operations; this is managed through exception handling for NumberFormatExceptions, which displays an error dialog when non-integer inputs are provided . Additionally, ensuring that the GUI remains responsive while processing these exceptions is crucial for usability, which can be managed by using Event Dispatch Thread (EDT) for GUI updates.

Event handling in Java GUI applications impacts performance and reliability significantly. Parsing user inputs and handling actions like button clicks are performed on the Event Dispatch Thread (EDT), and any long-running task on the EDT can freeze the UI, impacting performance. As seen in the Traffic Light Simulator and calculator examples, directly updating GUI components from event listener methods ensures immediate feedback to the user . However, this requires efficient event handling code to avoid blocking. Offloading long-running tasks to separate threads while ensuring thread-safe GUI updates can improve both performance and reliability.

The benefits of using a multithreaded approach in Java include improved application responsiveness and performance, especially in I/O-bound and high-latency tasks that can run concurrently without blocking the main thread. For computation tasks, multithreading can leverage multi-core processors to parallelize operations, as seen in the example where separate threads calculate squares and cubes of numbers . Challenges include complexities in synchronizing data access, potential for race conditions, and increased difficulty in debugging due to thread interactions. Proper handling of thread interruptions and resource locking is essential to avoid deadlocks and ensure data consistency.

File I/O operations in Java are crucial in applications involving persistent data storage, user interaction, or data visualization. For example, reading from a text file to display table data in a GUI leverages BufferedReader to handle data input efficiently, subsequently visualized through GUI components . Properly managing file I/O allows applications to persist user data across sessions and dynamically update visualizations based on updated file contents. Key considerations include ensuring data integrity, handling file access exceptions, and optimizing performance to manage large files or frequent reads/writes.

Adapter classes in Java offer a convenient way to handle only specific events when implementing listener interfaces that contain multiple methods. This eliminates the need to provide empty implementations for unused event-handling methods of an interface. In the MouseEventsDemo application, using a MouseAdapter allows handling of specific mouse events without the overhead of implementing all methods in the MouseListener interface . Adapter classes simplify code and improve readability by allowing developers to focus only on the relevant event-handling logic.

A doubly linked list allows bidirectional traversal, enabling efficient insertion and deletion operations at both ends as compared to a singly linked list, which only allows traversal in one direction. Deletion in a doubly linked list can be done in O(1) time when you have a reference to the node, compared to the O(n) time required if you need to traverse the singly linked list to find the node to delete. Additionally, a doubly linked list provides direct access to both the previous and next nodes, which is not possible in a singly linked list lacking back-pointers . However, a doubly linked list requires more memory due to the storage of an extra pointer per node.

Abstract classes in Java provide a flexible design approach that supports polymorphism by allowing a general structure that must be implemented in derived classes, enabling consistent behavior across different object types. In the design of shape classes (Rectangle, Triangle, Circle), the abstract Shape class defines the `printArea()` method without implementation, ensuring that each shape class must implement this method to calculate its area . This enforces a uniform interface for all shapes while permitting specific behavioral implementations, showcasing the power of polymorphism to extend functionality without modifying existing codebase structures.

Java Swing provides a rich set of GUI components that support platform-independent application development. It allows for highly customizable and flexible UIs, supporting event-driven programming which is key for interactivity . Compared to other GUI libraries like JavaFX or the now-deprecated AWT, Swing offers more sophisticated components and functionalities, though it might lack the modern aesthetics of JavaFX. Swing's lightweight nature and its ability to run on JVM on any OS give it a significant advantage over native UI toolkits, while its extensibility allows developers to enhance and customize components beyond default behaviors.

The producer-consumer problem illustrates the importance of inter-thread communication by showcasing how two threads can safely share resources without conflict. The critical considerations include ensuring that the producer does not produce new data when the buffer is full and the consumer does not consume when the buffer is empty, thus avoiding consumer starvation and producer blocking. In Java, this can be effectively managed using synchronized methods and the wait()/notify() mechanisms to control the access to shared resources, as demonstrated in the provided producer-consumer code . Proper handling of these synchronization primitives is crucial to prevent deadlocks and ensure smooth operation of the application.

You might also like