SREE VENKATESWARA
COLLEGE OF ENGINEERING(AUTONOMOUS)
NORTH RAJUPALEM, NELLORE (DIST)
AFFILIATED TO SBTET, AP
OOPS THROUGH
JAVA LAB MANUAL
(C 23 REGULATION)
DIPLOMA II
CME
IV SEMESTER
NAME OF THE STUDENT
ROLL.NO
YEAR
BRANCH
Name:
Roll No.:
Branch:
Year-Sem:
S.No Date Experiment Name Marks Instructor
Signature
Table of Contents
Name of the Experiment Page No.
1 Task 1: Exercise programs using java built-in data types.
2 Task2: Exercise programs using conditional statements and loop
statements
3 Task3: Exercise programs on I/O streams
4 Task4: Exercise programs on strings
5 Task 5: Exercise programs to create class and objects and adding
methods.
6 Task 6: Exercise programs using constructors and constructor
overloading
7 Task 7: Exercise programs on command line arguments.
8 Task 8: Exercise programs using concept of overloading methods
9 Task 9: Exercise programs on inheritance.
10 Task 10: Exercise programs using concept of method overriding
11 Task 11: Exercise on packages
12 Task 12: Exercise programs on interfaces.
13 Task 13: Exercise programs on collections.
14 Task 14: Exercise programs on exception handling.
15 Task 15: Exercise on multithreading.
16 Task 16: Exercise an applet.
17 Task 17: Exercise on AWT controls.
Experiment -1
Exercise programs using java built-in data types. Aim: write a java
program using built-in data types
Source code:
import java.util.Scanner;
public class RectangleArea {
public static void main(String[] args) {
// Declare variables using built-in data
types int length; // Integer for length
int width; // Integer for width
int area; // Integer for area
// Create a Scanner object for user input
Scanner scanner = new
Scanner(System.in);
// Ask for length and width
System.out.print("Enter the length of the rectangle: ");
length = scanner.nextInt();
System.out.print("Enter the width of the rectangle: ");
width = scanner.nextInt();
// Calculate the area
area = length *
width;
// Print the result
System.out.println("The area of the rectangle is: " + area);
// Close the scanner
scanner.close();
Input:
Output:
Experiment 2
Exercise programs using conditional statements and loop statements Aim: write
a java program using conditional statements and loop statements
a. write a java program using if statement and switch statement
source code:
import java.util.Scanner;
public class DayOfWeek {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); System.out.print("Enter a
number (1-7) for the day of the week: "); int day = scanner.nextInt();
// Using if statement to check for weekend or weekday
if (day == 6 || day == 7) {
System.out.println("It's a weekend!");
} else if (day >= 1 && day <= 5) {
System.out.println("It's a weekday!");
} else {
System.out.println("Invalid input! Please enter a number between 1 and 7."); return; //
Exit the program if input is invalid
// Using switch statement to display the day of the week switch
(day) {
case 1:
System.out.println("Monday"); break;
case 2:
System.out.println("Tuesday"); break;
case 3:
System.out.println("Wednesday"); break;
case 4:
System.out.println("Thursday"); break;
case 5:
System.out.println("Friday"); break;
case 6:
System.out.println("Saturday"); break;
case 7:
System.out.println("Sunday"); break;
default:
System.out.println("Invalid day");
scanner.close();
}
Input:
Output:
Experiment 3
Exercise programs on I/O streams
a. Aim: write a java program to give values to variables interactively through the keyboard.
Source code:
import java.util.Scanner;
public class InteractiveInput {
public static void main(String[] args) {
// Create a Scanner object to read input from the
keyboard Scanner scanner = new Scanner(System.in);
// Prompt for an integer
System.out.print("Enter an integer:
"); int intValue = scanner.nextInt();
// Prompt for a double
System.out.print("Enter a double:
");
double doubleValue = scanner.nextDouble();
// Clear the newline character from the input
buffer scanner.nextLine();
// Prompt for a string
System.out.print("Enter a string: ");
String stringValue =
scanner.nextLine();
// Display the values entered
System.out.println("\nYou entered:");
System.out.println("Integer: " + intValue);
System.out.println("Double: " +
doubleValue); System.out.println("String: " +
stringValue);
// Close the scanner
scanner.close();
Input:
Output:
b.write a program to handle files
source code:
import java.io.File;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class FileHandler {
public static void main(String[] args)
{ String filename = "example.txt";
// Step 1: Create and write to the file
try (FileWriter writer = new FileWriter(filename)) {
writer.write("Hello, World!\n");
writer.write("This is a simple file handling example in Java.\n");
writer.write("Enjoy coding!");
System.out.println("File created and data written successfully.");
} catch (IOException e) {
System.out.println("An error occurred while writing to the file: " + e.getMessage());
// Step 2: Read from the file
try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
String line;
System.out.println("\nReading from the file:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
System.out.println("An error occurred while reading from the file: " + e.getMessage());
// Step 3: Delete the file
File file = new
File(filename); if
(file.delete()) {
System.out.println("\nFile deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
Input:
Output:
c.write a java program reading and writing primitive data data types using data inputstream
and data output stream.
Source code:
Writing primitives to file:
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class WritePrimitives {
public static void main(String[] args) {
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("primitives.dat"))) {
dos.writeInt(123);
dos.writeFloat(3.14f);
dos.writeDouble(1.618);
dos.writeBoolean(true);
dos.writeChar('A');
dos.writeLong(9876543210L);
dos.writeShort(32000);
dos.writeByte(100);
} catch (IOException e) {
e.printStackTrace();
Input:
Output
reading:
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
public class ReadPrimitives {
public static void main(String[] args) {
try (DataInputStream dis = new DataInputStream(new FileInputStream("primitives.dat"))) {
int intValue = dis.readInt();
float floatValue = dis.readFloat();
double doubleValue =
dis.readDouble();
boolean booleanValue =
dis.readBoolean(); char charValue =
dis.readChar();
long longValue = dis.readLong();
short shortValue =
dis.readShort(); byte byteValue =
dis.readByte();
System.out.println("Int: " + intValue);
System.out.println("Float: " + floatValue);
System.out.println("Double: " + doubleValue);
System.out.println("Boolean: " + booleanValue);
System.out.println("Char: " + charValue);
System.out.println("Long: " + longValue);
System.out.println("Short: " + shortValue);
System.out.println("Byte: " + byteValue);
} catch (IOException e) {
e.printStackTrace();
Input:
Output:
Experiment 4
Exercise programs on strings
a. write a java program to arrange array of strings in ascending order
source code:
import java.util.Arrays;
public class SortStrings {
public static void main(String[] args) {
// Define an array of strings
String[] strings = {"banana", "apple", "orange", "kiwi", "grape"};
// Print the original array
System.out.println("Original array: " + Arrays.toString(strings));
// Sort the array in ascending
order Arrays.sort(strings);
// Print the sorted array
System.out.println("Sorted array: " + Arrays.toString(strings));
Input:
Output:
Experiment -5
Exercise programs to create class and objects and adding methods. a.Aim: write
a java program to create a class and create objects
source code:
public class Person {
// Attributes
String name;
int age;
// Constructor
public Person(String name, int age)
{ this.name = name;
this.age = age;
// Method to display person
details public void display() {
System.out.println("Name: " + name + ", Age: " + age);
// Main method to create objects
public static void main(String[] args)
// Create objects of the Person class
Person person1 = new Person("Alice",
30); Person person2 = new Person("Bob",
25);
// Display the details of the created
objects person1.display();
person2.display();
Input:
Output:
b.Aim:write a java program to create class adding methods and access class members.
Source code:
public class Person {
// Attributes
private String name;
private int age;
// Constructor
public Person(String name, int age)
{ this.name = name;
this.age = age;
// Getter method for name
public String getName() {
return name;
// Setter method for name
public void setName(String name)
{ this.name = name;
// Getter method for
age public int getAge()
{
return age;
// Setter method for age
public void setAge(int age)
this.age = age;
// Method to display person
details public void display() {
System.out.println("Name: " + name + ", Age: " + age);
// Main method to create objects and access class members
public static void main(String[] args) {
// Create objects of the Person class
Person person1 = new Person("Alice",
30); Person person2 = new Person("Bob",
25);
// Display the details of the created
objects person1.display();
person2.display();
// Modify the attributes using setter
methods person1.setName("Alice Smith");
person1.setAge(31);
// Access the modified attributes using getter methods
System.out.println("Updated Name of person1: " + person1.getName());
System.out.println("Updated Age of person1: " + person1.getAge());
// Display the updated details of
person1 person1.display();
Input:
Output:
Experiment-6
Exercise programs using constructors and constructor overloading a.Aim: write
a java program using default constructor
source code:
public class Person {
// Attributes
private String name;
private int age;
// Default constructor
public Person() {
// Initialize attributes with default
values this.name = "Unknown";
this.age = 0;
// Getter method for name
public String getName() {
return name;
// Setter method for name
public void setName(String name)
{ this.name = name;
}
// Getter method for
age public int getAge()
return age;
// Setter method for age
public void setAge(int age)
this.age = age;
// Method to display person
details public void display() {
System.out.println("Name: " + name + ", Age: " + age);
// Main method to create objects and access class members
public static void main(String[] args) {
// Create an object of the Person class using the default constructor
Person person1 = new Person();
// Display the details of the created
object person1.display();
// Modify the attributes using setter
methods person1.setName("Alice");
person1.setAge(30);
// Display the updated details of
person1 person1.display();
// Create another object using the default
constructor Person person2 = new Person();
// Display the details of the second
object person2.display();
Input:
Output:
b.write a java program using parameterized constructor
source code:
public class Person {
// Attributes
private String name;
private int age;
// Parameterized constructor
public Person(String name, int age)
{ this.name = name;
this.age = age;
// Getter method for name
public String getName() {
return name;
// Setter method for name
public void setName(String name)
{ this.name = name;
// Getter method for
age public int getAge()
return age;
}
// Setter method for age
public void setAge(int age)
this.age = age;
// Method to display person
details public void display()
System.out.println("Name: " + name + ", Age: " + age);
// Main method to create objects and access
class members public static void main(String[]
args) {
// Create objects of the Person class using the parameterized
constructor Person person1 = new Person("Alice", 30);
Person person2 = new Person("Bob", 25);
// Display the details of the created
objects person1.display();
person2.display();
// Modify the attributes using setter
methods person1.setName("Alice Smith");
person1.setAge(31);
// Access the modified attributes using getter methods
System.out.println("Updated Name of person1: " +
person1.getName()); System.out.println("Updated Age of person1:
" + person1.getAge());
// Display the updated details of
person1 person1.display();
Input:
Output:
c.write a java program using constructor overloading
source code:
public class Person {
// Attributes
private String name;
private int age;
// Default constructor
public Person() {
this.name =
"Unknown"; this.age =
0;
// Constructor with one parameter
(name) public Person(String name) {
this.name = name;
this.age = 0; // Default
age
// Constructor with two parameters (name and
age) public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Getter method for name
public String getName() {
return name;
// Setter method for name
public void setName(String name) {
this.name = name;
// Getter method for
age public int getAge()
return age;
// Setter method for age
public void setAge(int age)
this.age = age;
// Method to display person
details public void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
// Main method to create objects and access class members
public static void main(String[] args) {
// Create objects of the Person class using different constructors
Person person1 = new Person();
Person person2 = new Person("Alice");
Person person3 = new Person("Bob",
25);
// Display the details of the created
objects person1.display();
person2.display();
person3.display();
// Modify the attributes using setter
methods person1.setName("Charlie");
person1.setAge(20);
// Display the updated details of
person1 person1.display();
Input:
Output:
Experiment-7
Exercise programs on command line arguments. a.Aim: write a
java program using command line arguments.
Source code:
public class CommandLineArguments {
public static void main(String[] args) {
// Check if any arguments are
provided if (args.length == 0) {
System.out.println("No command line arguments provided.");
return;
// Process and display each command line argument
for (int i = 0; i < args.length; i++) {
String name = args[i];
System.out.println("Argument " + (i + 1) + ": " + name + " (Length: " + name.length() + ")");
Input:
Output:
b. write a java program to read data as command line arguments and update it into files.
Source code:
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class WriteToFile {
public static void main(String[] args) {
// Check if at least two arguments are provided: file name and data
if (args.length < 2) {
System.out.println("Usage: java WriteToFile <filename> <data>");
return;
// The first argument is the file
name String fileName = args[0];
// Concatenate the rest of the arguments as the data to be written to the file
StringBuilder data = new StringBuilder();
for (int i = 1; i < args.length; i++)
{ data.append(args[i]);
if (i < args.length - 1)
{ data.append(" ");
}
// Write the data to the file
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
writer.write(data.toString());
System.out.println("Data written to file: " + fileName);
} catch (IOException e) {
System.out.println("An error occurred while writing to the file.");
e.printStackTrace();
Input:
Output:
Experiment-8
a. Exercise programs using concept of overloading methods.
Aim: write a program to use method overloading
source code:
public class Calculator {
// Method to add two
integers public int add(int a,
int b) {
return a + b;
// Overloaded method to add three
integers public int add(int a, int b, int c) {
return a + b + c;
// Overloaded method to add two double
values public double add(double a, double b) {
return a + b;
// Overloaded method to add two strings
(concatenation) public String add(String a, String b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
// Using the add method with two integers
System.out.println("Addition of two integers: " + calc.add(5, 10));
// Using the add method with three integers
System.out.println("Addition of three integers: " + calc.add(5, 10, 15));
// Using the add method with two double values
System.out.println("Addition of two doubles: " + calc.add(5.5, 10.5));
// Using the add method with two strings
System.out.println("Addition of two strings: " + calc.add("Hello", " World"));
Input:
Output:
b. write a java program using method overloading using constructors
source code:
public class Person {
// Attributes
private String name;
private int age;
// Default constructor
public Person() {
this.name =
"Unknown"; this.age =
0;
// Constructor with one parameter
(name) public Person(String name) {
this.name = name;
this.age = 0; // Default
age
// Constructor with two parameters (name and
age) public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method to display person
details public void display() {
System.out.println("Name: " + name + ", Age: " + age);
public static void main(String[] args) {
// Create objects of the Person class using different constructors
Person person1 = new Person();
Person person2 = new Person("Alice");
Person person3 = new Person("Bob",
25);
// Display the details of the created
objects person1.display();
person2.display();
person3.display();
Input:
Output
Experiment-9
Excercise on inheritance.
a Aim: Write a java program using single inheritance
source code:
// Superclass (Parent
class) class Vehicle {
// Attribute
protected String brand;
// Constructor
public Vehicle(String brand)
{ this.brand = brand;
// Method
public void displayInfo() {
System.out.println("Brand: " +
brand);
// Subclass (Child class)
class Car extends Vehicle
// Additional
attribute private int
year;
public Car(String brand, int year) {
super(brand); // Call superclass
constructor this.year = year;
}
@Override
public void displayInfo() {
super.displayInfo(); // Call superclass
method System.out.println("Year: " + year);
public class Main
public static void main(String[] args) {
Car myCar = new Car("Toyota", 2022);
myCar.displayInfo();
Input
Outpu
b. write a java program using multiple inheritance
source code:
// Interface for Animal
behaviors interface Animal {
void eat();
void sleep();
// Interface for Vehicle
behaviors interface Vehicle {
void start();
void stop();
// Class implementing both Animal and Vehicle interfaces
class Robot implements Animal, Vehicle {
@Override
public void eat() {
System.out.println("Robot is eating electricity.");
@Override
public void sleep() {
System.out.println("Robot is in sleep mode.");
@Override
public void start() {
System.out.println("Robot starting up.");
@Override
public void stop() {
System.out.println("Robot shutting down.");
// Additional method specific to
Robot public void work() {
System.out.println("Robot is performing tasks.");
}
// Main class
public class Main
public static void main(String[] args) {
// Create an object of the class implementing multiple interfaces
Robot myRobot = new Robot();
// Call methods from Animal
interface myRobot.eat();
myRobot.sleep();
// Call methods from Vehicle
interface myRobot.start();
myRobot.stop();
// Call additional method specific to Robot class
myRobot.work();
Input:
Output:
Experiment-10
Exercise programs using concept of method overriding Aim: Write a
java program using the concept of method overriding Source code:
// Superclass (Parent
class) class Animal {
// Method to make a sound
public void makeSound() {
System.out.println("Animal makes a sound");
// Subclass (Child class)
class Dog extends Animal
// Method overriding: Dog's specific
sound @Override
public void makeSound () {
System.out.println("Dog barks");
// Main class
public class Main
public static void main(String[] args) {
// Create an object of the subclass (Dog)
Dog myDog = new Dog();
// Call the overridden
method
myDog.makeSound();
Input:
Output:
Experiment-11
write a java program to create and importing package
Source code:
myPackage
//MyClass.java
// File: myPackage/MyClass.java
// Package declaration
package myPackage;
// Class declaration
public class MyClass
// Method in MyClass
public void display() {
System.out.println("This is inside the myPackage package.");
myProgram/
├── MainProgram.java
└── myPackage/
└── MyClass.java
// File: myProgram/MainProgram.java
// Import statement to use MyClass from
myPackage import myPackage.MyClass;
public class MainProgram {
public static void main(String[] args) {
// Create an object of MyClass
MyClass obj = new
MyClass();
// Call the display method from
MyClass obj.display();
Input:
Output:
EXPERIMENT 12
AIM: write a java program to to illustrate multiple inheritance using
interfaces Source code:
// Interface for Animal
behaviors interface Animal {
void eat();
void sleep();
// Interface for Vehicle
behaviors interface Vehicle {
void start();
void stop();
// Class implementing both Animal and Vehicle interfaces
class Robot implements Animal, Vehicle {
@Override
public void eat() {
System.out.println("Robot is eating electricity.");
@Override
public void sleep() {
System.out.println("Robot is in sleep mode.");
}
@Override
public void start() {
System.out.println("Robot starting up.");
@Override
public void stop() {
System.out.println("Robot shutting down.");
// Additional method specific to
Robot public void work() {
System.out.println("Robot is performing tasks.");
// Main class
public class Main
public static void main(String[] args) {
// Create an object of the class implementing multiple interfaces
Robot myRobot = new Robot();
// Call methods from Animal
interface myRobot.eat();
myRobot.sleep();
// Call methods from Vehicle
interface myRobot.start();
myRobot.stop();
// Call additional method specific to Robot
class myRobot.work();
Input:
Output:
Experiment-13
Exercise programs on collections.
a.Aim: write a java program to search a student mark percentage based on pin number using
array list.
Source code:
import java.util.ArrayList;
// Student class representing each
student class Student {
private int pinNumber;
private String name;
private double percentage;
// Constructor to initialize student details
public Student(int pinNumber, String name, double percentage)
{ this.pinNumber = pinNumber;
this.name = name;
this.percentage = percentage;
// Getter method for
pinNumber public int
getPinNumber() {
return pinNumber;
// Method to get percentage
public double getPercentage() {
return percentage;
// Main class containing the program
logic public class StudentSearch {
public static void main(String[] args) {
// Create an ArrayList to store Student objects
ArrayList<Student> students = new
ArrayList<>();
// Adding sample student records
students.add(new Student(101, "Alice", 85.5));
students.add(new Student(102, "Bob", 77.8));
students.add(new Student(103, "Charlie",
91.2)); students.add(new Student(104, "David",
69.5));
// PIN number to
search int searchPin =
103;
// Search for the student's percentage based on PIN number
double foundPercentage = searchStudentPercentage(students, searchPin);
// Display the result
if (foundPercentage != -1) {
System.out.println("Percentage for PIN " + searchPin + ": " + foundPercentage);
} else {
System.out.println("Student with PIN " + searchPin + " not found.");
// Method to search for student's percentage based on PIN number
public static double searchStudentPercentage(ArrayList<Student> students, int pin) {
for (Student student : students) {
if (student.getPinNumber() == pin)
{ return student.getPercentage();
return -1; // Return -1 if student with given PIN is not found
Input:
Output
b.write a java program to create linked list to perform delete, insert and update data in linked list
with any application
source code:
import java.util.LinkedList;
import java.util.ListIterator;
// Employee class representing each employee
class Employee {
private int id;
private String
name;
private String position;
public Employee(int id, String name, String position) {
this.id = id;
this.name = name;
this.position =
position;
// Getters and setters for Employee
attributes public int getId() {
return id;
}
public void setId(int id)
{ this.id = id;
public String getName() {
return name;
public void setName(String name)
{ this.name = name;
public String getPosition()
{ return position;
public void setPosition(String position)
{ this.position = position;
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", position='" + position + '\''
+ '}';
// Main class containing the linked list
operations public class LinkedListOperations {
private LinkedList<Employee> employees;
public LinkedListOperations() {
employees = new
LinkedList<>();
// Method to add an employee to the linked list
public void addEmployee(Employee employee)
employees.add(employee);
// Method to delete an employee by ID
public void deleteEmployeeById(int id)
ListIterator<Employee> iterator = employees.listIterator();
while (iterator.hasNext()) {
Employee employee =
iterator.next(); if (employee.getId()
== id) {
iterator.remove();
System.out.println("Employee with ID " + id + " deleted.");
return;
System.out.println("Employee with ID " + id + " not found.");
// Method to update employee details by ID
public void updateEmployeeById(int id, String newName, String newPosition) {
ListIterator<Employee> iterator = employees.listIterator();
while (iterator.hasNext()) {
Employee employee =
iterator.next(); if (employee.getId()
== id) {
employee.setName(newName);
employee.setPosition(newPosition);
System.out.println("Employee details updated for ID " +
id); return;
System.out.println("Employee with ID " + id + " not found.");
// Method to display all employees in the linked list
public void displayEmployees() {
System.out.println("Employees:");
for (Employee employee : employees)
{ System.out.println(employee);
public static void main(String[] args) {
LinkedListOperations listOperations = new LinkedListOperations();
// Adding some sample employees
listOperations.addEmployee(new Employee(101, "Alice", "Manager"));
listOperations.addEmployee(new Employee(102, "Bob", "Developer"));
listOperations.addEmployee(new Employee(103, "Charlie", "Tester"));
// Display all employees
listOperations.displayEmployees();
// Update employee details
listOperations.updateEmployeeById(102, "Bobby", "Senior Developer");
// Display employees after update
listOperations.displayEmployees();
// Delete an employee
listOperations.deleteEmployeeById(101);
// Display employees after deletion
listOperations.displayEmployees();
Input:
Output:
c. write a java program to search an element from hash table.
Source code:
import java.util.Hashtable;
public class HashtableSearchExample {
public static void main(String[] args) {
Hashtable<Integer, String> hashtable = new Hashtable<>();
hashtable.put(1, "Alice");
hashtable.put(2, "Bob");
hashtable.put(3, "Charlie");
hashtable.put(4, "David");
hashtable.put(5, "Eve");
int keyToSearch = 3;
if (hashtable.containsKey(keyToSearch)) {
String value =
hashtable.get(keyToSearch);
System.out.println("Element with key " + keyToSearch + " found: " + value);
} else {
System.out.println("Element with key " + keyToSearch + " not found.");
Input:
Output:
D.write a java program to sorting employee details using hash map
Source code:
import java.util.*;
// Employee class representing each employee
class Employee {
private int id;
private String name;
private String
position;
public Employee(int id, String name, String position) {
this.id = id;
this.name = name;
this.position =
position;
public int getId()
{ return id;
public String getName() {
return name;
}
public String getPosition() {
return position;
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", position='" + position + '\''
+ '}';
public class TreeMapSortingExample {
public static void main(String[] args) {
// Create a TreeMap to store Employee objects sorted by ID
TreeMap<Integer, Employee> treeMap = new
TreeMap<>();
// Adding sample employee details
treeMap.put(102, new Employee(102, "Bob", "Developer"));
treeMap.put(101, new Employee(101, "Alice", "Manager"));
treeMap.put(103, new Employee(103, "Charlie", "Tester"));
treeMap.put(104, new Employee(104, "David",
"Engineer"));
// Displaying employee details after sorting by ID
System.out.println("Employee details sorted by ID:");
for (Map.Entry<Integer, Employee> entry : treeMap.entrySet()) {
System.out.println("ID: " + entry.getKey() + ", Details: " + entry.getValue());
Input:
Output:
Experiment-14
Exercise on exception handling a.write a program
to illustrate exception handling source code:
import java.util.Scanner;
public class ExceptionHandlingExample {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in); int[] numbers = { 1, 2,
3, 4, 5 };
System.out.print("Enter the index to retrieve the corresponding number: ");
try {
// Try block: code that may throw an
exception int index = scanner.nextInt();
int number = numbers[index];
System.out.println("Number at index " + index + " is: " + number);
} catch (ArrayIndexOutOfBoundsException e) {
// Catch block: handle the exception
System.out.println("Error: Index out of bounds. Please enter a valid index.");
} catch (Exception e) {
// Catch block: handle any other exceptions
System.out.println("Error: Something went wrong. Please try again.");
} finally {
// Finally block: cleanup code that always executes
scanner.close();
System.out.println("Scanner closed.");
System.out.println("End of program.");
Input:
Output:
b. write a java program to illustrate exception handling using multiple catch statements.
Source code:
import java.util.Scanner;
public class MultipleCatchExample {
public static void main(String[] args) {
Scanner scanner = new
Scanner(System.in);
try {
System.out.print("Enter a number:
"); int number = scanner.nextInt();
// Perform division
int result = 10 / number;
System.out.println("Result of division: " + result);
// Attempting to access an array element out of bounds
int[] array = { 1, 2, 3 };
System.out.print("Enter an index to retrieve element from array: ");
int index = scanner.nextInt();
System.out.println("Element at index " + index + ": " + array[index]);
} catch (ArithmeticException e) {
// Catch block for arithmetic exceptions
System.out.println("Error: Division by zero or other arithmetic error.");
} catch (ArrayIndexOutOfBoundsException e) {
// Catch block for array index out of bounds exceptions
System.out.println("Error: Index is out of bounds for the array.");
} catch (Exception e) {
// Catch block for any other exceptions
System.out.println("Error: Something went wrong. Please try again.");
} finally {
// Cleanup code (closing
scanner) scanner.close();
System.out.println("Scanner closed.");
System.out.println("End of program.");
Input:
Output:
c.Write a java program to illustarate exception handling using nested try
source code:
class NestedTry {
// main method
public static void main(String args[])
// Main try block
try {
// initializing array
int a[] = { 1, 2, 3, 4, 5 };
// trying to print element at index
5 System.out.println(a[5]);
// try-block2 inside another try
block try {
// performing division by
zero int x = a[2] / 0;
catch (ArithmeticException e2) {
System.out.println("division by zero is not possible");
}
}
catch (ArrayIndexOutOfBoundsException e1) {
System.out.println("ArrayIndexOutOfBoundsException");
System.out.println("Element at such index does not
exists");
Input:
Output:
Experiment-15
Excercise on multithreading
a.write a java program to create single a thread by extending the thread class
source code:
// Define a class that extends
Thread class MyThread extends
Thread {
// Override the run() method to define the thread's
behavior @Override
public void run() {
System.out.println("Thread " + Thread.currentThread().getId() + " is running.");
for (int i = 1; i <= 5; i++) {
System.out.println("Count in Thread " + Thread.currentThread().getId() + ": " + i);
try {
Thread.sleep(1000); // Simulate some work by sleeping for 1 second
} catch (InterruptedException e) {
System.out.println("Thread " + Thread.currentThread().getId() + " interrupted.");
System.out.println("Thread " + Thread.currentThread().getId() + " is finished.");
public class SingleThreadExample {
public static void main(String[] args)
// Create an instance of MyThread
MyThread thread = new
MyThread();
// Start the thread
thread.start();
// Main thread continues execution while MyThread runs concurrently
System.out.println("Main thread continues...");
// Wait for MyThread to finish
(optional) try {
thread.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted while waiting for MyThread to finish.");
System.out.println("Main thread is finished.");
Input:
Output:
b.write a java program to create a single thread by implementing the runnable interface
source code:
// Define a class that implements
Runnable class MyRunnable implements
Runnable {
// Override the run() method to define the thread's
behavior @Override
public void run() {
System.out.println("Thread " + Thread.currentThread().getId() + " is running.");
for (int i = 1; i <= 5; i++) {
System.out.println("Count in Thread " + Thread.currentThread().getId() + ": " + i);
try {
Thread.sleep(1000); // Simulate some work by sleeping for 1 second
} catch (InterruptedException e) {
System.out.println("Thread " + Thread.currentThread().getId() + " interrupted.");
System.out.println("Thread " + Thread.currentThread().getId() + " is finished.");
public class SingleThreadRunnableExample {
public static void main(String[] args) {
// Create an instance of MyRunnable
MyRunnable myRunnable = new
MyRunnable();
// Create a Thread object with MyRunnable
instance Thread thread = new
Thread(myRunnable);
// Start the thread
thread.start();
// Main thread continues execution while MyRunnable runs concurrently
System.out.println("Main thread continues...");
// Wait for MyRunnable to finish
(optional) try {
thread.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted while waiting for MyRunnable to finish.");
System.out.println("Main thread is finished.");
Input:
Output:
c.write a java program to create multiple threads
source code:
// Define a class that extends
Thread class MyThread extends
Thread {
// Constructor to assign a name to the
thread public MyThread(String name) {
super(name); // Call superclass (Thread) constructor with thread name
// Override the run() method to define the thread's
behavior @Override
public void run() {
System.out.println("Thread " + getName() + " is running.");
for (int i = 1; i <= 5; i++) {
System.out.println("Count in Thread " + getName() + ": " + i);
try {
Thread.sleep(1000); // Simulate some work by sleeping for 1 second
} catch (InterruptedException e) {
System.out.println("Thread " + getName() + " interrupted.");
System.out.println("Thread " + getName() + " is finished.");
}
public class MultipleThreadsExample {
public static void main(String[] args) {
// Create multiple instances of MyThread and start them
MyThread thread1 = new MyThread("Thread-1");
MyThread thread2 = new MyThread("Thread-2");
MyThread thread3 = new MyThread("Thread-3");
// Start threads
thread1.start();
thread2.start();
thread3.start();
// Main thread continues execution while other threads run concurrently
System.out.println("Main thread continues...");
// Optionally, wait for threads to finish
try {
thread1.join();
thread2.join();
thread3.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted while waiting for threads to finish.");
System.out.println("Main thread is finished.");
}
Input:
Output:
d.write a java program to illustrate thread priorities
source code:
// Define a Runnable class
class MyRunnable implements Runnable {
private String name;
// Constructor to assign a name to the
thread public MyRunnable(String name) {
this.name = name;
}
// Override the run() method to define the thread's
behavior @Override
public void run() {
System.out.println("Thread " + name + " is running with priority " +
Thread.currentThread().getPriority());
for (int i = 1; i <= 5; i++) {
System.out.println("Count in Thread " + name + ": " + i);
try {
Thread.sleep(1000); // Simulate some work by sleeping for 1 second
} catch (InterruptedException e) {
System.out.println("Thread " + name + "
interrupted.");
System.out.println("Thread " + name + " is finished.");
public class ThreadPriorityExample {
public static void main(String[] args) {
// Create instances of Thread and set their priorities
Thread thread1 = new Thread(new MyRunnable("Thread-1"));
Thread thread2 = new Thread(new MyRunnable("Thread-2"));
Thread thread3 = new Thread(new MyRunnable("Thread-3"));
// Set thread priorities
thread1.setPriority(Thread.MIN_PRIORITY); // 1
thread2.setPriority(Thread.NORM_PRIORITY); // 5 (default)
thread3.setPriority(Thread.MAX_PRIORITY); // 1
// Start threads
thread1.start();
thread2.start();
thread3.start();
// Main thread continues execution
System.out.println("Main thread continues...");
Input:
Output:
e.write a java program to illustrate inter thread communication
source code:
import java.util.LinkedList;
import java.util.Queue;
// Define a shared queue
class class SharedQueue {
private Queue<Integer> queue;
private int capacity;
public SharedQueue(int capacity) {
this.queue = new
LinkedList<>(); this.capacity =
capacity;
// Synchronized method to add an item to the
queue public synchronized void produce(int item)
// Wait while the queue is full
while (queue.size() == capacity)
try {
wait(); // Release the lock and wait for notification
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread interrupted while waiting to produce.");
// Add item to the queue
queue.offer(item);
System.out.println("Produced: " +
item);
notify(); // Notify consumer thread that an item is produced
// Synchronized method to remove an item from the queue
public synchronized int consume() {
// Wait while the queue is
empty while (queue.isEmpty())
try {
wait(); // Release the lock and wait for notification
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("Thread interrupted while waiting to consume.");
// Remove and return item from the
queue int item = queue.poll();
System.out.println("Consumed: " +
item);
notify(); // Notify producer thread that an item is consumed
return item;
// Define a producer class that implements
Runnable class Producer implements Runnable {
private SharedQueue
sharedQueue; private int value =
0;
public Producer(SharedQueue sharedQueue)
{ this.sharedQueue = sharedQueue;
@Override
public void run() {
while (true) {
sharedQueue.produce(value++);
try {
Thread.sleep(1000); // Simulate some processing time
} catch (InterruptedException e) {
System.out.println("Thread interrupted while
sleeping.");
// Define a consumer class that implements
Runnable class Consumer implements Runnable {
private SharedQueue sharedQueue;
public Consumer(SharedQueue sharedQueue)
{ this.sharedQueue = sharedQueue;
@Override
public void run() {
while (true) {
sharedQueue.consume();
try {
Thread.sleep(1500); // Simulate some processing time
} catch (InterruptedException e) {
System.out.println("Thread interrupted while sleeping.");
public class InterThreadCommunicationExample {
public static void main(String[] args) {
SharedQueue sharedQueue = new SharedQueue(5);
// Create and start producer and consumer threads
Thread producerThread = new Thread(new Producer(sharedQueue));
Thread consumerThread = new Thread(new Consumer(sharedQueue));
producerThread.start();
consumerThread.start();
Input:
Output:
Experiment-16.
Excercise on applets
a.write a java program to create simple applet to display different shapes with colors
source code:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class ShapesApplet extends Applet {
@Override
public void init() {
// Initialization code if needed
@Override
public void paint(Graphics g) {
// Set background color
setBackground(Color.white);
// Draw different shapes with different
colors g.setColor(Color.red);
g.fillRect(50, 50, 100, 80); // Draw a filled rectangle
g.setColor(Color.blue);
g.fillOval(200, 50, 80, 80); // Draw a filled oval
g.setColor(Color.green);
g.fillRect(100, 150, 120, 80); // Draw another filled rectangle
g.setColor(Color.orange);
g.fillRoundRect(250, 150, 100, 80, 20, 20); // Draw a filled round rectangle
g.setColor(Color.magenta);
g.fillArc(400, 150, 100, 80, 0, 180); // Draw a filled arc
g.setColor(Color.cyan);
g.drawLine(50, 300, 250, 300); // Draw a line
g.setColor(Color.black);
g.drawString("Shapes with Colors", 50, 350); // Draw text
Input:
Output:
b.write a java program an applet program to design simple animation
source code:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
public class SimpleAnimation extends Applet implements Runnable {
private int x = 50; // Initial x-coordinate of the object
private int y = 50; // Initial y-coordinate of the
object private int dx = 5; // Change in x for each step
private int dy = 3; // Change in y for each step
private int delay = 50; // Delay between updates in milliseconds
private Thread animator; // Thread for animation
@Override
public void init() {
setBackground(Color.white);
@Override
public void start() {
animator = new Thread(this);
animator.start(); // Start the thread
@Override
public void stop() {
animator = null; // Stop the thread
@Override
public void run() {
while (true) {
// Update the
coordinates x += dx;
y += dy;
// Check if the object reaches the
boundaries if (x > getWidth() - 50 || x < 0)
dx = -dx; // Reverse direction in x-axis
if (y > getHeight() - 50 || y < 0) {
dy = -dy; // Reverse direction in y-axis
repaint(); // Request to redraw the
applet try {
Thread.sleep(delay); // Delay for animation effect
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
@Override
public void paint(Graphics g)
{ g.setColor(Color.red);
g.fillOval(x, y, 50, 50); // Draw a red filled circle
Input:
Output:
Experiment-17.Excercise on AWT controls
a.write an applet program to handle key
events source code:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class KeyEventApplet extends Applet implements KeyListener {
private int x = 50; // Initial x-coordinate of the rectangle
private int y = 50; // Initial y-coordinate of the rectangle
@Override
public void init() {
setBackground(Color.white);
addKeyListener(this); // Add key listener to the applet
setFocusable(true); // Set focusable to handle key
events
@Override
public void keyPressed(KeyEvent e)
{ int key = e.getKeyCode();
// Move the rectangle based on arrow key presses
if (key == KeyEvent.VK_LEFT)
{ x -= 10; // Move left
} else if (key == KeyEvent.VK_RIGHT)
{ x += 10; // Move right
} else if (key == KeyEvent.VK_UP)
{ y -= 10; // Move up
} else if (key == KeyEvent.VK_DOWN)
{ y += 10; // Move down
repaint(); // Request to redraw the applet
@Override
public void keyReleased(KeyEvent e) {
// Handle key release if needed
@Override
public void keyTyped(KeyEvent e) {
// Handle key typed if needed
@Override
public void paint(Graphics g) {
g.setColor(Color.red);
g.fillRect(x, y, 50, 30); // Draw a red filled rectangle
Input;
Output:
b.write an applet program to handle mouse events
source code:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseEventApplet extends Applet implements MouseListener {
private int x = -1; // x-coordinate of the mouse click
private int y = -1; // y-coordinate of the mouse click
@Override
public void init() {
setBackground(Color.white);
addMouseListener(this); // Add mouse listener to the applet
@Override
public void mouseClicked(MouseEvent e) {
x = e.getX(); // Get x-coordinate of the mouse click
y = e.getY(); // Get y-coordinate of the mouse click
repaint(); // Request to redraw the applet
@Override
public void mousePressed(MouseEvent e) {
// Handle mouse pressed event if needed
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void paint(Graphics g)
{ if (x != -1 && y != -1) {
g.setColor(Color.blue);
g.fillOval(x - 25, y - 25, 50, 50); // Draw a blue filled circle at mouse click coordinates
Input:
Output:
c.write an applet program to illustrate text field and button control
source code:
import java.applet.Applet;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TextFieldButtonApplet extends Applet implements ActionListener {
private TextField textField;
private Button submitButton;
private String userInput =
"";
@Override
public void init() {
setBackground(Color.white);
// Create a text field
textField = new TextField(20); // 20 columns wide
@Override
public void actionPerformed(ActionEvent e)
{ if (e.getSource() == submitButton) {
userInput = textField.getText(); // Get text from the text
field repaint(); // Request to redraw the applet
}
@Override
public void paint(Graphics g) {
g.setColor(Color.black);
g.drawString("Enter your name:", 50,
50);
g.setColor(Color.blue);
g.drawString("You entered: " + userInput, 50, 100);
Input:
Output:
d.write an applet program to illustrare check box and list control
source code:
import java.applet.Applet;
import java.awt.Checkbox;
import java.awt.Color;
import java.awt.List;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class CheckboxListApplet extends Applet implements ItemListener {
private Checkbox checkbox1, checkbox2, checkbox3;
private List itemList;
@Override
public void init() {
setBackground(Color.white);
// Create checkboxes
checkbox1 = new Checkbox("Option 1");
checkbox2 = new Checkbox("Option 2");
checkbox3 = new Checkbox("Option 3");
// Add checkboxes to
applet add(checkbox1);
add(checkbox2);
add(checkbox3);
// Register item listener for
checkboxes
checkbox1.addItemListener(this);
checkbox2.addItemListener(this);
checkbox3.addItemListener(this);
// Create list
itemList = new List(4, true); // 4 visible rows, multi-selection enabled
itemList.add("Item 1");
itemList.add("Item 2");
itemList.add("Item 3");
itemList.add("Item 4");
// Add list to applet
add(itemList);
@Override
public void itemStateChanged(ItemEvent e) {
// Handle checkbox item state
change if (e.getSource() ==
checkbox1) {
System.out.println("Checkbox 1 is " + (checkbox1.getState() ? "checked" : "unchecked"));
} else if (e.getSource() == checkbox2) {
System.out.println("Checkbox 2 is " + (checkbox2.getState() ? "checked" : "unchecked"));
} else if (e.getSource() == checkbox3) {
System.out.println("Checkbox 3 is " + (checkbox3.getState() ? "checked" : "unchecked"));
// Handle list item selection
change if (e.getSource() ==
itemList) {
String[] selectedItems = itemList.getSelectedItems();
System.out.print("Selected items: ");
for (String item : selectedItems)
{ System.out.print(item + " ");
System.out.println();
}
}
Input:
Output: