0% found this document useful (0 votes)
19 views71 pages

csm java lab manual

This document is a lab manual for the OOP Using Java course at Keshav Memorial Engineering College for the academic year 2024-25. It includes various programming experiments demonstrating concepts such as classes, inheritance, exception handling, and threading in Java. Each experiment provides code examples and expected outputs to illustrate the respective programming concepts.

Uploaded by

sridharpf
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)
19 views71 pages

csm java lab manual

This document is a lab manual for the OOP Using Java course at Keshav Memorial Engineering College for the academic year 2024-25. It includes various programming experiments demonstrating concepts such as classes, inheritance, exception handling, and threading in Java. Each experiment provides code examples and expected outputs to illustrate the respective programming concepts.

Uploaded by

sridharpf
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/ 71

Keshav Memorial Engineering College

A unit of Keshav Memorial Technical Educational Society (KMTES)


(Approved by AICTE, New Delhi & Affiliated to Osmania University, Hyderabad)
D.No. 10 TC-111, Kachavanisingaram (V), Ghatkesar (M), Medchal-Malkajgiri, Telangana – 500 088

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 :

This is to Certify that this is a bonafide record of practical work done by

Mr./Miss of B.E Branch Semester

bearing with Hall ticket no. during the academic year

in the laboratory.

Internal Examiner External Examiner

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

Exp. Experiment Date of Date of Signature


No. Experiment submission ofthe Faculty
1

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;

public Calculator(int value) {


this.value = value;
}

public int add(int number) {


value += number;
return value;
}

public int subtract(int number) {


value -= number;
return value;
}

public int multiply(int number1) {


return value * number1;
}

public int multiply(int number1, int number2) {


return number1 * number2;
}

public static void main(String[] args) {


Calculator calc = new Calculator(10);
System.out.println("Initial value: " + calc.value);
System.out.println("After addition (10 + 5): " + calc.add(5));
System.out.println("After subtraction (15 - 3): " + calc.subtract(3));
System.out.println("Multiplication with one argument (12 * 3): " + calc.multiply(3));
System.out.println("Multiplication with two arguments (3 * 4): " + calc.multiply(3, 4));
}
}
Output:

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());

buffer.append(" Welcome to Java.");


System.out.println("Updated StringBuffer: " + buffer.toString());
}
}
Output:

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.

a)Extending Thread class


Aim: To write a JAVA program that creates threads by extending Thread class .First
thread display “Good Morning “every 1 sec, the second thread displays “Hello “every 2
seconds and the third display “Welcome” every 3 seconds ,(Repeat the same by
implementing Runnable).
Programs:
(i) Creating multiple threads using Threadclass
class A extends Thread
{
public void run()
{
try
{
for(int i=1;i<=10;i++)
{
sleep(1000);
System.out.println("good
morning");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
class B extends Thread
{
public void run()
{
try
{
for(int j=1;j<=10;j++)
{
sleep(2000);
System.out.println("hello"
);
}
}
catch(Exception e)
{
System.out.println(e);

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;

synchronized int get()

if(!b) try

wait();

catch(Exception e)
{
System.out.println(e);
}
System.out.println("Got:"+n); b=false;

notify(); returnn;

synchronized void put(int n)

if(b) try

wait();
}
catch(Exception e)
{
System.out.println(e);
}
this.n=n; b=true;

System.out.println("Put:"+n); notify();

29
}

class Producer implements Runnable

A a1;

Thread t1; producer(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;

public synchronized void write(String message) {


while (hasMessage) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
content = message;
hasMessage = true;
System.out.println("Produced: " + message);
notify();
}

public synchronized void read() {


while (!hasMessage) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println("Consumed: " + content);
hasMessage = false;
notify();
}
}

public class SimpleInterThreadCommunication {


public static void main(String[] args) {
Message message = new Message();

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();
}
}
});

Thread consumer = new Thread(() -> {


for (int i = 0; i < 5; i++) {
message.read();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
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.*;

public class Main {


public static void main(String[] args) {
TreeSet<Integer> treeSet = new TreeSet<>();

treeSet.add(10);
treeSet.add(20);
treeSet.add(30);
treeSet.add(10);
treeSet.add(5);
treeSet.add(25);

System.out.println("TreeSet elements (Sorted):");


for (Integer num : treeSet) {
System.out.print(num + " ");
}

System.out.println("\nSmallest element: " + treeSet.first());


System.out.println("Largest element: " + treeSet.last());

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());
}

System.out.println("\nDoes key 2 exist? " + map.containsKey(2));


System.out.println("Does value 'Apple' exist? " + map.containsValue("Apple"));
}
}
Output:

42
18. A program using Enumeration and Comparator interfaces
import java.util.*;

class Person {
String name;
int age;

Person(String name, int age) {


this.name = name;
this.age = age;
}

@Override
public String toString() {
return name + ": " + age;
}
}

class AgeComparator implements Comparator<Person> {


public int compare(Person p1, Person p2) {
return Integer.compare(p1.age, p2.age);
}
}

public class Main {


public static void main(String[] args) {
Vector<Person> vector = new Vector<>();
vector.add(new Person("Alice", 25));

43
vector.add(new Person("Bob", 30));
vector.add(new Person("Charlie", 20));

System.out.println("Vector using Enumeration:");


Enumeration<Person> enumeration = vector.elements();
while (enumeration.hasMoreElements()) {
System.out.println(enumeration.nextElement());
}

System.out.println("\nVector sorted by age:");


Collections.sort(vector, new AgeComparator());
for (Person person : vector) {
System.out.println(person);
}
}
}

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.print("Enter your name: ");


String name = reader.readLine();

System.out.print("Enter your age: ");


int age = Integer.parseInt(reader.readLine());

System.out.println("\nHello " + name + "! You are " + age + " years old.");

BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));

writer.write("Name: " + name);


writer.newLine();
writer.write("Age: " + age);
writer.close();

System.out.println("\nData written to output.txt");

} 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.*;

public class Main {


public static void main(String[] args) {
try {
FileOutputStream fileOutputStream = new FileOutputStream("output.dat");
DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);

String message = "Hello, this is a test message!";


int number = 12345;

dataOutputStream.writeUTF(message);
dataOutputStream.writeInt(number);

dataOutputStream.flush();

long fileSize = new File("output.dat").length();


System.out.println("Number of bytes written to the file: " + fileSize);

dataOutputStream.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} }}
Output:

47
22. A program to illustrate ByteArrayI/O Streams.
import java.io.*;

public class Main {


public static void main(String[] args) {
try {
String message = "Hello, this is a byte array I/O example!";

// Writing to ByteArrayOutputStream
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byteArrayOutputStream.write(message.getBytes());

// Converting byte array to string (for display)


byte[] byteArray = byteArrayOutputStream.toByteArray();
System.out.println("Data written to ByteArrayOutputStream: " + new String(byteArray));

// Reading from ByteArrayInputStream


ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
int byteData;
System.out.println("Data read from ByteArrayInputStream:");
while ((byteData = byteArrayInputStream.read()) != -1) {
System.out.print((char) byteData);
}
byteArrayOutputStream.close();
byteArrayInputStream.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
} }}
Output:

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.*;

class Calculator extends JFrame implements ActionListener {


// Create a frame
static JFrame f;

// Create a textfield
static JTextField l;

// Store operator and operands


String s0, s1, s2;

// 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 an object of the Calculator class


Calculator c = new Calculator();

// Create a textfield
l = new JTextField(16);

// Set the textfield to non-editable


l.setEditable(false);

// Create number buttons and operators


JButton b0, b1, b2, b3, b4, b5, b6, b7, b8, b9;

53
JButtonba, bs, bd, bm, be, beq, beq1;

// Create number buttons


b0 = new JButton("0");
b1 = new JButton("1");
b2 = new JButton("2");
b3 = new JButton("3");
b4 = new JButton("4");
b5 = new JButton("5");
b6 = new JButton("6");
b7 = new JButton("7");
b8 = new JButton("8");
b9 = new JButton("9");

// Equals button
beq1 = new JButton("=");

// Create operator buttons


ba = new JButton("+");
bs = new JButton("-");
bd = new JButton("/");
bm = new JButton("*");
beq = new JButton("C");

// Create decimal point button


be = new JButton(".");

// Create a panel
JPanel p = new JPanel();

// Add action listeners


JButton[] buttons = {b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, ba, bs, bd, bm, beq, beq1, be};
for (JButtonbutton : buttons) {
button.addActionListener(c);
}

// Add elements to panel


p.add(l);
p.add(ba);
p.add(b1);
p.add(b2);
p.add(b3);
p.add(bs);

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

// Set background of panel


p.setBackground(Color.blue);

// Add panel to frame


f.add(p);

f.setSize(200, 220);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}

public void actionPerformed(ActionEvent e) {


String s = e.getActionCommand();

// If the value is a number or decimal point


if ((s.charAt(0) >= '0' &&s.charAt(0) <= '9') || s.charAt(0) == '.') {
if (!s1.equals("")) {
s2 += s;
} else {
s0 += s;
}
l.setText(s0 + s1 + s2);
} else if (s.equals("C")) {
// Clear the text
s0 = s1 = s2 = "";
l.setText("");
} else if (s.equals("=")) {
// Perform calculation
double result = 0;

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");
}

l.setText(s0 + s1 + s2 + "=" + result);


s0 = String.valueOf(result);
s1 = s2 = "";

} catch (NumberFormatException | ArithmeticException ex) {


l.setText("Error");
s0 = s1 = s2 = "";
}
} else {
// If an operator is pressed
if (s1.equals("") && !s0.equals("")) {
s1 = s;
} else if (!s1.equals("") && !s2.equals("")) {
// Evaluate the expression
double result = 0;

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;

public class RecursiveFibonacciSwing {


public static void main(String[] args) {
// Create the frame
JFrame frame = new JFrame("Recursive Fibonacci Calculator");
frame.setSize(400, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// Create components
JLabelinputLabel = new JLabel("Enter a number:");
JTextFieldinputField = new JTextField(10);
JButtoncalculateButton = new JButton("Calculate");
JLabelresultLabel = new JLabel("Result: ");

// Add action listener to the button


calculateButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
int n = Integer.parseInt(inputField.getText());
if (n < 0) {
JOptionPane.showMessageDialog(frame, "Please enter a non-negative integer.", "Error",
JOptionPane.ERROR_MESSAGE);
return;
}
int result = fibonacci(n);
resultLabel.setText("Result: " + result);
} catch (NumberFormatException ex) {
JOptionPane.showMessageDialog(frame, "Invalid input. Please enter an integer.",
"Error", JOptionPane.ERROR_MESSAGE);
}
}
});

// Add components to the frame


JPanel panel = new JPanel();
panel.add(inputLabel);
panel.add(inputField);

58
panel.add(calculateButton);
panel.add(resultLabel);
frame.add(panel);

// Make the frame visible


frame.setVisible(true);
}

// Recursive Fibonacci function


public static int fibonacci(int n) {
if (n == 0) {
return 0;
} else if (n == 1) {
return 1;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
}

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;

public class Digital_clock extends JFrame {

private JLabeltimeLabel;
private JLabeldateLabel;

public Digital_clock() {
setTitle("Digital Clock");
setSize(500, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);

// Create a panel to hold the time and date labels


JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
panel.setLayout(new BorderLayout());

// Create a label to display the time


timeLabel = new JLabel();
timeLabel.setFont(new Font("Arial", Font.PLAIN, 60));
timeLabel.setHorizontalAlignment(SwingConstants.CENTER);
timeLabel.setVerticalAlignment(SwingConstants.CENTER);
timeLabel.setForeground(Color.RED);

// Create a label to display the date


dateLabel = new JLabel();
dateLabel.setFont(new Font("Arial", Font.PLAIN, 20));
dateLabel.setHorizontalAlignment(SwingConstants.CENTER);
dateLabel.setVerticalAlignment(SwingConstants.CENTER);

60
dateLabel.setForeground(Color.WHITE);

// Add the time and date labels to the panel


panel.add(timeLabel, BorderLayout.CENTER);
panel.add(dateLabel, BorderLayout.SOUTH);

// Set the panel's background color


panel.setBackground(Color.BLACK);

// Add the panel to the frame


add(panel);

// 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();
}

private void updateTimeAndDate() {


// Get the current time and format it
Calendar calendar = Calendar.getInstance();
SimpleDateFormattimeFormatter = new SimpleDateFormat("HH:mm:ss");
String time = timeFormatter.format(calendar.getTime());

// Get the current date and format it


SimpleDateFormatdateFormatter = new SimpleDateFormat("EEE, MMM dd, yyyy");
String date = dateFormatter.format(calendar.getTime());

// Update the time and date labels


timeLabel.setText(time);
dateLabel.setText(date);
}

public static void main(String[] args) {


Digital_clock clock = new Digital_clock();
clock.setVisible(true);
}
}

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

Label label = new Label("File Name :");


label.setBounds(100,0,100,40);
this.add(label);

file = new TextField();


file.setBounds(200,0,200,40);
this.add(file);

text = new TextArea("",0,0,TextArea.SCROLLBARS_NONE);


text.setBounds(50,75,400,300);
this.add(text);

Button read = new Button("Read From File");


read.setBounds(75,400,150,25);
this.add(read);
read.addActionListener(this);

Button write = new Button("Write To File");


write.setBounds(275,400,150,25);
this.add(write);
write.addActionListener(this);
}
//Function to call functions for operations selected
public void actionPerformed(ActionEvent e)
{
String button = e.getActionCommand();
if(button.equals("Read From File"))

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;

public class CalendarComboBox {


public static void main(String[] args) {
JFrame frame = new JFrame("Calendar using JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setLayout(new GridLayout(4, 2));

JLabelyearLabel = new JLabel("Year:");


JLabelmonthLabel = new JLabel("Month:");
JLabeldayLabel = new JLabel("Day:");
JLabelselectedDateLabel = new JLabel("Selected Date:");

Integer[] years = new Integer[100];


for (int i = 0; i< 100; i++) {
years[i] = 1925 + i;
}

String[] months = new String[12];


for (int i = 0; i< 12; i++) {
months[i] = String.format("%02d", i + 1);
}

Integer[] days = new Integer[31];


for (int i = 0; i< 31; i++) {
days[i] = i + 1;
}

JComboBox<Integer>yearComboBox = new JComboBox<>(years);


JComboBox<String>monthComboBox = new JComboBox<>(months);
JComboBox<Integer>dayComboBox = new JComboBox<>(days);

JButtonshowDateButton = new JButton("Show Date");


JLabeldateDisplay = new JLabel("");

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

a) Mouse event handling


import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);

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

Mouse clicking event

Actual output

71

You might also like