csm java lab manual
csm java lab manual
DEPARTMENT OF CSE(AI&ML)
II B.E-III Sem
OOP Using Java Lab Manual
Subject Code:PC352CS
Academic Year: 2024-25
Name
RollNo
Branch/Sec
Year
Sem
1
Department :
in the laboratory.
Principal
2
Experiment- 1. A program to illustrate the concept of class with constructors, methods and
overloading.
class Calculator {
private double number1;
private double number2;
public Calculator(double number1, double number2) {
this.number1 = number1;
this.number2 = number2;
}
public Calculator() {
this.number1 = 0;
this.number2 = 0;
}
public double add() {
return number1 + number2;
}
public double add(double number3) {
return number1 + number2 + number3;
}}
public class Main {
public static void main(String[] args) {
Calculator calc1 = new Calculator(5, 10);
System.out.println("Addition: " + calc1.add());
System.out.println("Addition with 3rd number: " + calc1.add(15));
}}
Output:
3
INDEX
10
11
12
13
4
Exp. Date of Date of Signatureof
No. Experiment submission the Faculty
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
5
Experiment- 1 A program to illustrate the concept of class with constructors, methods and
overloading
public class Calculator {
private int value;
6
Experiment- 2. A program to illustrate the concept of Inheritance and Dynamic polymorphism.
class Animal {
public void sound() {
System.out.println("Animal makes a sound");
}}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}}
class Cat extends Animal {
@Override
public void sound() {
System.out.println("Cat meows");
}}
public class Main {
public static void main(String[] args) {
Animal myAnimal;
myAnimal = new
Dog();
myAnimal.sound();
myAnimal = new Cat();
myAnimal.sound();
}}
Output:
7
- 3. A program to show the concept of packages.
package mypackage;
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int subtract(int a, int b) {
return a - b;
}}
import mypackage.Calculator;
public class Main {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Addition: " + calc.add(10, 5));
System.out.println("Subtraction: " + calc.subtract(10, 5));
}}
Output:
8
Experiment- 4 :Write a Java program to demonstrate the Interfaces and Abstract Classes.
a) Abstract classes
Aim: To write a java program for abstract class to find areas of different shapes .
Program:
abstract class Shape
{
abstract double area();
}
class Rectangle extends Shape
{
double
l=12.5,b=2.5;
double area()
{
return l*b;
}
}
class Triangle extends Shape
{
double
b=4.2,h=6.5;
double area()
{
return 0.5*b*h;
}
}
class Square extends Shape
{
double
s=6.5;
double area()
{
return 4*s;
}
}
class Shapedemo
{
public static void main(String[] args)
{
Rectangle r1=new
Rectangle(); Triangle t1=new
9
Triangle(); Square s1=new
Square();
System.out.println("The area of rectangle is:
"+r1.area()); System.out.println("The area of triangle
is: "+t1.area());System.out.println("The area of square
is: "+s1.area());
}
}
Output:
10
Experiment- Aim: To write a Java program to implement Interface.
Programs:
(i) First form of interfaceimplementation
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("B's method");
}
}
class C extends B
{
public void callme()
{
System.out.println("C's method");
}
}
class Interfacedemo
{
public static void main(String args[])
{
C c1=new
C();
c1.display();
c1.callme();
}
}
Actual Output:
11
(ii) Second form of interfaceimplementation
interface D
{
void display();
}
interface E extends D
{
void show();
}
class A
{
void callme()
{
System.out.println("This is in callme method");
}
}
class B extends A implements E
{
public void display()
{
System.out.println("This is in display method");
}
public void show()
{
System.out.println("This is in show method");
}
}
class C extends B
{
void call()
{
System.out.println("This is in call method");
}
}
class Interfacedemo
{
public static void main(String args[])
{
C c1=new
C();
c1.display();
c1.show();
c1.callme();
c1.call();
12
}
}
Actual Output:
13
(iii) Third form of interfaceimplementation
interface A
{
void display();
}
class B implements A
{
public void display()
{
System.out.println("This is in B's method");
}
}
class C implements A
{
public void display()
{
System.out.println("This is C's method");
}
}
class interfacedemo
{
public static void main(String args[])
{
B b1=new B(); C c1=new C(); b1.display();
c1.display();
}
}
Actual Output:
14
(iv) Fourth form of interfaceimplementation
interface A
{
void display();
}
interface B
{
void callme();
}
interface C extends A,B
{
void call();
}
class D implements C
{
public void display()
{
System.out.println("interface A");
}
public void callme()
{
System.out.println("interface B");
}
public void call()
{
System.out.println("interface C");
}
}
class Interfacedemo
{
public static void main(String args[])
{
D d1=new D();
d1.display();
d1.callme();
d1.call();
}
}
Actual Output:
15
Experiment -5 :Write a Java program to implement the concept of exception handling.
a) Exception handlingmechanism
Aim: To write a Java program that describes exception handling mechanism.
Program:
class Trydemo
{
public static void main(String args[])
{
try
{
int
a=10,b=0;
int c=a/b;
System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("After the catch statement");
}
}
Actual Output:
16
b) Illustrating multiple catchclauses
Aim: To write a Java program Illustrating Multiple catch clauses.
Program:
class Multitrydemo
{
public static void main(String args[])
{
try
{
int
a=10,b=5;
int c=a/b;
int d[]={0,1};
System.out.println(d[10]
); System.out.println(c);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("After the catch statement");
}
}
Actual Output:
17
Experiment-6. A program to illustrate user define exception using stack.
class StackUnderflowException extends Exception {
public StackUnderflowException(String message) {
super(message);
}}
class SimpleStack {
private int[] stack;
private int top;
public SimpleStack(int size) {
stack = new int[size];
top = -1;
}
public void push(int value) {
if (top == stack.length - 1) {
System.out.println("Stack Overflow: Cannot push " + value);
return;
}
stack[++top] = value;
}
public int pop() throws StackUnderflowException {
if (top == -1) {
throw new StackUnderflowException("Stack Underflow: Cannot pop, the stack is empty.");
}
return stack[top--];
}
public void display() {
if (top == -1) {
System.out.println("Stack is empty.");
return;
18
}
System.out.print("Stack elements: ");
for (int i = 0; i <= top; i++) {
System.out.print(stack[i] + " ");
}
System.out.println();
}}
public class Main {
public static void main(String[] args) {
SimpleStack stack = new SimpleStack(3);
stack.push(10);
stack.push(20);
stack.push(30);
stack.display();
try {
System.out.println("Popped: " + stack.pop());
System.out.println("Popped: " + stack.pop());
System.out.println("Popped: " + stack.pop());
System.out.println("Popped: " + stack.pop());
} catch (StackUnderflowException e) {
System.out.println(e.getMessage());
} }}
Output:
19
Experiment-7. A program to illustrate user define exception for evaluating a post fix expression.
import java.util.Stack;
class InvalidPostfixExpressionException extends Exception {
public InvalidPostfixExpressionException(String message) {
super(message);
}}
class DivisionByZeroException extends Exception {
public DivisionByZeroException(String message) {
super(message);
}}
class PostfixEvaluator {
public static int evaluate(String expression) throws InvalidPostfixExpressionException,
DivisionByZeroException {
Stack<Integer> stack = new Stack<>();
for (char ch : expression.toCharArray()) {
if (Character.isDigit(ch)) {
stack.push(ch - '0');
} else {
if (stack.size() < 2) {
throw new InvalidPostfixExpressionException("Invalid postfix expression.");
}
int operand2 = stack.pop();
int operand1 = stack.pop();
switch (ch) {
case '+':
stack.push(operand1 + operand2);
break;
case '-':
stack.push(operand1 - operand2);
break;
20
case '*':
stack.push(operand1 * operand2);
break;
case '/':
if (operand2 == 0) {
throw new DivisionByZeroException("Division by zero is not allowed.");
}
stack.push(operand1 / operand2);
break;
default:
throw new InvalidPostfixExpressionException("Unknown operator: " + ch);
} } }
if (stack.size() != 1) {
throw new InvalidPostfixExpressionException("Invalid postfix expression.");
}
return stack.pop();
}}
public class Main {
public static void main(String[] args) {
String expression = "23*54*+9-";
try {
int result = PostfixEvaluator.evaluate(expression);
System.out.println("Result of postfix evaluation: " + result);
} catch (InvalidPostfixExpressionException | DivisionByZeroException e) {
System.out.println("Error: " + e.getMessage());
} }}
Output:
21
Experiment-8. A program to illustrate to handle string in java using String and StringBuffer.
public class Main {
public static void main(String[] args) {
String str1 = "Hello, ";
String str2 = "World!";
String result1 = str1.concat (str2);
System.out.println("Using String: " + result1);
System.out.println("Original String: " + str1);
StringBuffer buffer = new StringBuffer("Hello, ");
buffer.append("World!");
System.out.println("Using StringBuffer: " + buffer.toString());
22
9. A program to illustrate manipulating array in java
public class Main {
public static void main(String[] args) {
int[] numbers = new int[5];
// Initializing array elements
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;
numbers[3] = 40;
numbers[4] = 50;
System.out.println("Original Array:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
// Modifying an element
numbers[2] = 100;
System.out.println("\nArray after modifying an element:");
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
// Adding an element (by creating a new array)
int[] newArray = new int[numbers.length + 1];
for (int i = 0; i < numbers.length; i++) {
newArray[i] = numbers[i];
}
newArray[newArray.length - 1] = 60;
System.out.println("\nArray after adding an element:");
for (int i = 0; i < newArray.length; i++) {
System.out.print(newArray[i] + " ");
23
}
// Removing an element (by creating a new array)
int[] smallerArray = new int[numbers.length - 1];
int indexToRemove = 1;
for (int i = 0, j = 0; i < numbers.length; i++) {
if (i != indexToRemove) {
smallerArray[j++] = numbers[i];
}
}
System.out.println("\nArray after removing an element:");
for (int i = 0; i < smallerArray.length; i++) {
System.out.print(smallerArray[i] + " ");
}
}
}
Output:
24
Experiment-10. Write a Java program to illustrate the concept of threading using Thread
Class and runnable Interface.
25
}
}
}
class C extends Thread
{
public void run()
{
try
{
for(int k=1;k<=10;k++)
{
sleep(3000);
System.out.println("welcome"
);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class Threaddemo
{
public static void main(String args[])
{
A a1=new
A(); B
b1=new B();
C c1=new C();
a1.start();
b1.start();
c1.start();
}
}
Output:
26
(ii) Creating multiple threads using Runnableinterface
class A implements Runnable
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
Thread.sleep(1000);
System.out.println("good
morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class B implements Runnable
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
Thread.sleep(2000);
System.out.println("hello"
);
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class C implements Runnable
{
public void run()
{
try
27
{
for(int k=1;k<=10;k++)
{
Thread.sleep(3000);
System.out.println("welcome"
);
}
}
catch(Exception e)
{
System.out.println(e);
}}
}
class Runnabledemo
{
public static void main(String args[])
{
A a1=new
A(); B
b1=new B();
C c1=new C();
Thread t1=new
Thread(a1); Thread
t2=new Thread(b1);
Thread t3=new
Thread(c1); t1.start();
t2.start();
t3.start();
}
}
Output:
28
Experiment – 11 :Write a Java program to illustrate the concept of Thread
synchronization.
a)Producer-Consumer problem
Aim: To write a Java program on Producer Consumer Problem using Threads.
Program:
class A
{
int n;
boolean b=false;
if(!b) try
wait();
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Got:"+n); b=false;
notify(); returnn;
if(b) try
wait();
}
catch(Exception e)
{
System.out.println(e);
}
this.n=n; b=true;
System.out.println("Put:"+n); notify();
29
}
A a1;
this.a1=a1;
t1=new Thread(this); t1.start();
}
public void run()
{
for(int i=1;i<=10;i++)
{
a1.put(i);
}
}
}
class Consumer implements Runnable
{
A a1;
Thread
t1;
Consum
er(A a1)
{
this.a1=a1;
t1=new
Thread(this);
t1.start();
}
public void run()
{
for(int j=1;j<=10;j++)
{
a1.get();
}
}
}
class Interdemo
30
{
public static void main(String args[])
{
A a1=new A();
Producer p1=new
Producer(a1); Consumer
c1=new Consumer(a1);
}
}
Output:
31
Experiment – 12. A program to illustrate inter thread communication.
class Message {
private String content;
private boolean hasMessage = false;
32
Thread producer = new Thread(() -> {
String[] messages = {"Hello", "World", "Java", "is", "fun"};
for (String msg : messages) {
message.write(msg);
try {
Thread.sleep(500);
} catch (InterruptedException e) {a
Thread.currentThread().interrupt();
}
}
});
producer.start();
consumer.start();
}
}
Output:
33
Experiment- 13 :Write a Java Program that reads a line of integers, and then displays
each integer, and the sum of all the integers (Use String Tokenizer class of java. util).
Aim:To write a Java program that reads a line of integers and displays each
integer and sum of all the integers.
Program:
import
java.util.StringTokenize
r; public class Main
{
public static void main(String[] args) {
StringTokenizerst = new
StringTokenizer("5 6 7"); int sum=0;
while (st.hasMoreTokens()) {
int
num=Integer.valueOf(st.nextTok
en()); sum=sum+num;
}
System.out.println(sum);
}
}
Output:
34
a) Write a Java program to illustrate collection classes LinkedList
Aim:To write a Java program on LinkedList.
Program:
import java.util.*;
public class JavaExample{
public static void main(String args[]){
LinkedList<String> list=new
LinkedList<String>();
//Adding elements to the
Linked list list.add("Steve");
list.add("Carl");
list.add("Raj");
//Adding an element to the first
position list.addFirst("Negan");
//Adding an element to the
lastposition
list.addLast("Rick");
//Adding an element to the 3rd
position list.add(2,"Glenn");
//Iterating LinkedList
Iterator<String> iterator=list.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
}
Output:
35
14. A program using Linked list class
import java.io.*;
import java.util.*;
class LLDemo
{
public static void main(String args[])
throws IOException
{
//create an empty linked list
LinkedList ll=new LinkedList();
//add element to ll
ll.add("America");
ll.add("India");
ll.add("Srilanka");
ll.add("Australia");
ll.add("England");
//display the Linked List
System.out.println("Linked List="+ll);
//vars
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String element;
int pos,choice=0;
//menu
while(choice<4)
{
System.out.println("LInked LIST Operations");
System.out.println("1 Insert Element");
System.out.println("2 Remove Element");
36
System.out.println("3 change Element");
System.out.println("4 EXIT");
System.out.println("Your Choice");
choice=Integer.parseInt(br.readLine());
//perform a task using Switch
switch(choice)
{
case 1:
System.out.println("Enter element");
element=br.readLine();
System.out.println("Enter Position");
pos=Integer.parseInt(br.readLine());
ll.add(pos,element);
break;
case 2:
System.out.println("Enter position");
pos=Integer.parseInt(br.readLine());
ll.remove(pos);
break;
case 3:
System.out.println("Enter new Element");
element=br.readLine();
System.out.println("Enter Position");
pos=Integer.parseInt(br.readLine());
ll.set(pos,element);
break;
default:
return;
37
}
System.out.println("LINKED LIST="+ll);
}
}
}
Output:
38
15. A program using Tree set class
import java.util.*;
treeSet.add(10);
treeSet.add(20);
treeSet.add(30);
treeSet.add(10);
treeSet.add(5);
treeSet.add(25);
treeSet.remove(20);
System.out.println("TreeSet after removing 20:");
for (Integer num : treeSet) {
System.out.print(num + " ");
}
39
System.out.println("\nSubset from 5 to 25:");
SortedSet<Integer> subset = treeSet.subSet(5, 25);
for (Integer num : subset) {
System.out.print(num + " ");
}
}
}
Output:
40
16. A program using Hash set and Iterator classes.
import java.util.*;
public class Main {
public static void main(String[] args) {
HashSet<String> hashSet = new HashSet<>();
hashSet.add("Apple");
hashSet.add("Banana");
hashSet.add("Cherry");
hashSet.add("Apple"); // Duplicate value, won't be added
hashSet.add("Date");
System.out.println("HashSet elements:");
Iterator<String> iterator = hashSet.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
System.out.println("\nHashSet after removing 'Banana':");
hashSet.remove("Banana");
iterator = hashSet.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}}
Output:
41
17. A program using Map classes.
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Banana");
map.put(3, "Cherry");
map.put(4, "Date");
map.put(2, "Blueberry"); // This will overwrite the value for key 2
System.out.println("Map elements:");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println("\nValue for key 3: " + map.get(3));
map.remove(4);
System.out.println("\nMap after removing key 4:");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
42
18. A program using Enumeration and Comparator interfaces
import java.util.*;
class Person {
String name;
int age;
@Override
public String toString() {
return name + ": " + age;
}
}
43
vector.add(new Person("Bob", 30));
vector.add(new Person("Charlie", 20));
Output:
44
19.A program to illustrate Buffered I/O streams and Buffered reader
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\nHello " + name + "! You are " + age + " years old.");
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Output:
45
20. Write a Java program to read text from file from a specify index or skipping byte using
file Input stream
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("input.txt");
int skipBytes = 10; // Number of bytes to skip before reading
fileInputStream.skip(skipBytes); // Skipping the specified bytes
int character;
System.out.println("Content after skipping " + skipBytes + " bytes:");
while ((character = fileInputStream.read()) != -1) {
System.out.print((char) character);
}
fileInputStream.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} }}
Output:
46
21. Write a Java program to determine number of byte return to file using data output
stream.
import java.io.*;
dataOutputStream.writeUTF(message);
dataOutputStream.writeInt(number);
dataOutputStream.flush();
dataOutputStream.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} }}
Output:
47
22. A program to illustrate ByteArrayI/O Streams.
import java.io.*;
// Writing to ByteArrayOutputStream
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(message.getBytes());
48
23. A program to illustrate the usage of Serialization.
import java.io.*;
class Person implements Serializable {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + "}";
}}
public class Main {
public static void main(String[] args) {
Person person = new Person("John", 30);
try {
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
System.out.println("Serialization successful, person object saved to person.ser");
FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Person deserializedPerson = (Person) in.readObject();
in.close();
fileIn.close();
49
System.out.println("Deserialization successful, retrieved object: " + deserializedPerson);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} }}
Output:
50
24. An application involving GUI with different controls, menus and event handling.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame("GUI Application with Controls and Menus");
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(new FlowLayout());
JLabel label = new JLabel("Enter your name:");
JTextField textField = new JTextField(20);
JButton button = new JButton("Submit");
JCheckBox checkBox = new JCheckBox("Subscribe to newsletter");
JRadioButton radioButton1 = new JRadioButton("Option 1");
JRadioButton radioButton2 = new JRadioButton("Option 2");
ButtonGroup group = new ButtonGroup();
group.add(radioButton1);
group.add(radioButton2);
panel.add(label);
panel.add(textField);
panel.add(button);
panel.add(checkBox);
panel.add(radioButton1);
panel.add(radioButton2);
51
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem newItem = new JMenuItem("New");
JMenuItem exitItem = new JMenuItem("Exit");
fileMenu.add(newItem);
fileMenu.add(exitItem);
menuBar.add(fileMenu);
frame.setJMenuBar(menuBar);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String name = textField.getText();
boolean subscribed = checkBox.isSelected();
String selectedOption = radioButton1.isSelected() ? "Option 1" : "Option 2";
JOptionPane.showMessageDialog(frame, "Name: " + name + "\nSubscribed: " + subscribed +
"\nSelected: " + selectedOption);
}
});
newItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(frame, "New option clicked");
}
});
exitItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
} });
frame.setVisible(true);
}}
Output:
52
Experiment- 25 :A program to implement a simple calculator using grid layout manager
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
// Create a textfield
static JTextField l;
// Default constructor
Calculator() {
s0 = s1 = s2 = "";
}
// Main function
public static void main(String args[]) {
// Create a frame
f = new JFrame("Calculator");
try {
// Set look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
System.err.println(e.getMessage());
}
// Create a textfield
l = new JTextField(16);
53
JButtonba, bs, bd, bm, be, beq, beq1;
// Equals button
beq1 = new JButton("=");
// Create a panel
JPanel p = new JPanel();
54
p.add(b4);
p.add(b5);
p.add(b6);
p.add(bm);
p.add(b7);
p.add(b8);
p.add(b9);
p.add(bd);
p.add(be);
p.add(b0);
p.add(beq);
p.add(beq1);
f.setSize(200, 220);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
55
try {
double operand1 = Double.parseDouble(s0);
double operand2 = Double.parseDouble(s2);
switch (s1) {
case "+" -> result = operand1 + operand2;
case "-" -> result = operand1 - operand2;
case "*" -> result = operand1 * operand2;
case "/" -> result = operand1 / operand2;
default -> throw new IllegalArgumentException("Unknown operator");
}
try {
double operand1 = Double.parseDouble(s0);
double operand2 = Double.parseDouble(s2);
switch (s1) {
case "+" -> result = operand1 + operand2;
case "-" -> result = operand1 - operand2;
case "*" -> result = operand1 * operand2;
case "/" -> result = operand1 / operand2;
default -> throw new IllegalArgumentException("Unknown operator");
}
s0 = String.valueOf(result);
s1 = s;
s2 = "";
56
} catch (NumberFormatException | ArithmeticException ex) {
l.setText("Error");
s0 = s1 = s2 = "";
}
}
l.setText(s0 + s1 + s2);
}
}
}
Sample output
Actual output
57
Experiment- 26: A program to implement recursive Fibonacci method using swing
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
// Create components
JLabelinputLabel = new JLabel("Enter a number:");
JTextFieldinputField = new JTextField(10);
JButtoncalculateButton = new JButton("Calculate");
JLabelresultLabel = new JLabel("Result: ");
58
panel.add(calculateButton);
panel.add(resultLabel);
frame.add(panel);
Sample output
Output
59
Experiment- 27: A program to display digital clock using swing
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.Timer;
private JLabeltimeLabel;
private JLabeldateLabel;
public Digital_clock() {
setTitle("Digital Clock");
setSize(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
60
dateLabel.setForeground(Color.WHITE);
// Use a Timer to update the time and date labels every second
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
updateTimeAndDate();
}
});
timer.start();
}
61
Sample output:
Output:
62
Experiment- 28: A program to read from a file and write to a file using Applet
/* Java Program to Perform Read and Write Operations */
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class File extends Applet implements ActionListener
{
TextField file;
TextArea text;
//Initialize the applet
public void init()
{
setBackground(Color.white);
setLayout(null);
63
{
read();
}
else
{
write();
}
}
//Function to Read the File
public void read()
{
try
{
FileReaderobj = new FileReader(file.getText());
int i;
text.setText("");
while((i=obj.read())!= -1)
{
text.setText(text.getText()+(char)i);
}
obj.close();
}
catch(Exception E)
{
text.setText(E.getMessage());
}
}
//Function to Write to the File
public void write()
{
try
{
FileWriterobj = new FileWriter(file.getText());
obj.write(text.getText());
obj.close();
text.setText("File Written Successfully");
}
catch(Exception E)
{
text.setText(E.getMessage());
}
}
}
64
/*
<applet code = File.class width=500 height=500>
</applet>
*/
Sample output
65
66
Actual output
67
Experiment- 29 :A program to display a calendar using JCombo box
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
showDateButton.addActionListener(new ActionListener() {
68
@Override
public void actionPerformed(ActionEvent e) {
int year = (int) yearComboBox.getSelectedItem();
String month = (String) monthComboBox.getSelectedItem();
int day = (int) dayComboBox.getSelectedItem();
dateDisplay.setText("Selected Date: " + year + "-" + month + "-" + day);
}
});
frame.add(yearLabel);
frame.add(yearComboBox);
frame.add(monthLabel);
frame.add(monthComboBox);
frame.add(dayLabel);
frame.add(dayComboBox);
frame.add(showDateButton);
frame.add(dateDisplay);
frame.setVisible(true);
}
}
Sample output
Actual output
69
Experiment- 30: A program to illustrate event listener interfaces
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
} });
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
70
Sample output
Mouse entered event
Actual output
71