Javapartb

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

PART-B

2. Develop a program with various types of exceptions and their handling.

import java.io.*;

public class ExceptionHandlingDemo {

public static void handleException(String operation, Exception e) {

System.out.println("Error during " + operation + ": " + e.getMessage());

public static void main(String[] args) {

try {

int result = 10 / 0;

System.out.println("Result of division is " + result);

} catch (ArithmeticException e) {

handleException("division by zero", e);

try {

int[] arr = new int[]{1, 2, 3};

int element = arr[5];

System.out.println("Element at index 5 is " + element);

} catch (ArrayIndexOutOfBoundsException e) {

handleException("array index out of bounds", e);

try {

int number = Integer.parseInt("abc");

System.out.println("Conversion to integer is " + number);

} catch (NumberFormatException e) {

handleException("number format", e);

}
Output:

3. Create a GUI program with buttons and implement event handling for mouse
clicks.

import javax.swing.*;

import java.awt.event.*;

public class ButtonClickApp {

public static void main(String[] args) {

JFrame frame = new JFrame("Button Click Event Handling");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel panel = new JPanel();

JButton button1 = new JButton("Button 1"), button2 = new JButton("Button 2");

panel.add(button1);

panel.add(button2);

frame.add(panel);

frame.setSize(300, 200);

frame.setVisible(true);

ActionListener listener = e -> JOptionPane.showMessageDialog(frame,


e.getActionCommand() + " Clicked!");

button1.addActionListener(listener);

button2.addActionListener(listener);

Output:
4. Design a GUI program with various components like buttons, labels, and text
fields.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleGuiApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Simple GUI Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel(new GridLayout(3, 2, 10, 10));
JLabel inputLabel = new JLabel("Enter your name:");
JTextField textField = new JTextField(20);
JButton button = new JButton("Submit");
JLabel resultLabel = new JLabel("");
panel.add(inputLabel);
panel.add(textField);
panel.add(button);
panel.add(resultLabel);
frame.add(panel);
frame.setSize(400, 200);
frame.setVisible(true);
button.addActionListener(e -> {
String name = textField.getText();
resultLabel.setText(name.isEmpty() ? "Please enter your name." : "Hello, " +
name + "!");
});
}
}

Output:
5. Write a java program that works as a simple calculator. Use a Grid Layout to
arrange Buttons for digits and for the + - * %operations. Add a text field to display
the result.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleCalculator {
private static JTextField displayField = new JTextField();
private static double firstNumber = 0, secondNumber = 0;
private static String operator = "";
private static boolean isOperatorClicked = false;
public static void main(String[] args) {
JFrame frame = new JFrame("Simple Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setLayout(new BorderLayout());
displayField.setEditable(false);
displayField.setHorizontalAlignment(SwingConstants.RIGHT);
frame.add(displayField, BorderLayout.NORTH);
JPanel buttonPanel = new JPanel(new GridLayout(4, 4, 10, 10));
String[] buttonLabels = {"7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-",
"0", "C", "=", "+"};
for (String label : buttonLabels) {
JButton button = new JButton(label);
button.addActionListener(new ButtonClickListener());
buttonPanel.add(button);
}
frame.add(buttonPanel);
frame.setVisible(true);
}
static class ButtonClickListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
switch (command) {
case "C": resetCalculator(); break;
case "=": performCalculation(); break;
case "+": case "-": case "*": case "/": operatorClicked(command); break;
default: displayField.setText(displayField.getText() + command);
}
}

private void resetCalculator() {


displayField.setText("");
firstNumber = secondNumber = 0; operator = ""; isOperatorClicked = false;
}

private void performCalculation() {


secondNumber = Double.parseDouble(displayField.getText());
displayField.setText(String.valueOf(calculate(firstNumber, secondNumber,
operator)));
firstNumber = secondNumber; operator = ""; isOperatorClicked = false;
}

private void operatorClicked(String command) {


if (!isOperatorClicked) {
firstNumber = Double.parseDouble(displayField.getText());
isOperatorClicked = true;
} else {
secondNumber = Double.parseDouble(displayField.getText()); firstNumber
= calculate(firstNumber, secondNumber, operator);
}
operator = command; displayField.setText("");
}
}

private static double calculate(double num1, double num2, String op) {


switch (op) {
case "+": return num1 + num2;
case "-": return num1 - num2;
case "*": return num1 * num2;
case "/": return num2 != 0 ? num1 / num2 : showError("Cannot divide by
zero");
default: return 0;
}
}

private static double showError(String message) {


JOptionPane.showMessageDialog(null, message);
return firstNumber;
}
}
OUTPUT:

8. Develop a program to demonstrate the use of various Collection classes,


iterators, working with maps, and generic collections.

import java.util.*;
public class CollectionDemo {
public static void main(String[] args) {
// Demonstrate ArrayList and LinkedList
List<String> arrayList = new ArrayList<>(Arrays.asList("Apple", "Banana",
"Orange"));
List<String> linkedList = new LinkedList<>(Arrays.asList("Mango", "Grapes"));
// Print ArrayList and LinkedList
System.out.println("ArrayList:\n" + String.join("\n", arrayList));
System.out.println("\nLinkedList:\n" + String.join("\n", linkedList));
// Demonstrate HashSet and TreeSet
Set<Integer> hashSet = new HashSet<>(Arrays.asList(5, 3, 8));
Set<Integer> treeSet = new TreeSet<>(Arrays.asList(7, 2, 6));
// Print HashSet and TreeSet
System.out.println("\nHashSet:\n" + hashSet);
System.out.println("\nTreeSet:\n" + treeSet);
// Demonstrate HashMap and TreeMap
Map<String, Integer> hashMap = new HashMap<>();
hashMap.put("One", 1);
hashMap.put("Three", 3);
hashMap.put("Five", 5);
Map<String, Integer> treeMap = new TreeMap<>();
treeMap.put("Two", 2);
treeMap.put("Four", 4);
// Print HashMap and TreeMap
hashMap.forEach((k,v) -> System.out.println(k + " : " + v));
treeMap.forEach((k,v) -> System.out.println(k + " : " + v));
}
}
Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy