Output:
Experiment-1
Aim: To write a program using Java built-in data types.
Source Code:
public class DataTypeProgram {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
int sum = num1 + num2;
System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);
float floatNum = 3.14f;
double doubleNum = 2.71828;
double product = floatNum * doubleNum;
System.out.println("Product of " + floatNum + " and " + doubleNum + " is: " + product);
char letter = 'A';
System.out.println("The letter is: " + letter);
boolean isTrue = true;
System.out.println("The boolean value is: " + isTrue);
String message = "Hello, World!";
System.out.println("The message is: " + message);
}
Output:
Experiment-2
Aim: To write a program on conditional statements and loop statements.
Source Code:
public class ConditionalLoopProgram {
public static void main(String[] args) {
int sum = 0;
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
sum += i;
System.out.println("The sum of even numbers from 1 to 10 is: " + sum);
}
Experiment-3
Aim: To write a program on I/O Streams
Source Code:
import java.io.*;
import java.util.Scanner;
public class IOStreamExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 1. Reading data through the keyboard
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
String fileName = "data.txt";
// 2. Writing primitive data to file using DataOutputStream
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(fileName))) {
dos.writeUTF(name);
dos.writeInt(age);
System.out.println("Data written to file successfully.");
} catch (IOException e) {
System.out.println("Error writing data: " + e.getMessage());
// 3. Reading primitive data from file using DataInputStream
try (DataInputStream dis = new DataInputStream(new FileInputStream(fileName))) {
String readName = dis.readUTF();
int readAge = dis.readInt();
Output:
System.out.println("Read from file: Name = " + readName + ", Age = " + readAge);
} catch (IOException e) {
System.out.println("Error reading data: " + e.getMessage());
// 4. Writing text to a file using FileOutputStream
try (FileOutputStream fos = new FileOutputStream("output.txt")) {
String content = "Name: " + name + ", Age: " + age;
fos.write(content.getBytes());
System.out.println("Text written to output.txt successfully.");
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
// 5. Reading text from the file using FileInputStream
try (FileInputStream fis = new FileInputStream("output.txt")) {
System.out.println("Reading from output.txt:");
int ch;
while ((ch = fis.read()) != -1) {
System.out.print((char) ch);
System.out.println();
} catch (IOException e) {
System.out.println("Error reading from file: " + e.getMessage());
scanner.close();
}
Experiment-4
Aim: To write a program on Strings.
Source Code:
public class StringProgram {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String result1 = str1 + ", " + str2;
System.out.println("Concatenated string: " + result1);
int length = str1.length();
System.out.println("Length of str1: " + length);
String substring = str2.substring(0, 3);
System.out.println("Substring of str2: " + substring);
String uppercase = str1.toUpperCase();
System.out.println("Uppercase string: " + uppercase);
String lowercase = str2.toLowerCase();
System.out.println("Lowercase string: " + lowercase);
boolean contains = str1.contains("ell");
System.out.println("str1 contains 'ell': " + contains);
boolean equals = str1.equals(str2);
System.out.println("str1 equals str2: " + equals);
String replaced = str1.replace("l", "L");
System.out.println("Replaced string: " + replaced);
String[] parts = str2.split("r");
System.out.println("Split string parts:");
for (String part : parts) {
System.out.println(part);
}
Output:
Experiment-5
Aim: To write a program to create class and objects and adding methods
Source Code:
public class Rectangle {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
public double getLength() {
return length;
public double getWidth() {
return width;
public void setLength(double length) {
this.length = length;
public void setWidth(double width) {
this.width = width;
public double calculateArea() {
return length * width;
public double calculatePerimeter() {
return 2 * (length + width);
}
Output:
//write this new java file
public class ClassAndObjectProgram {
public static void main(String[] args) {
Rectangle rectangle1 = new Rectangle(5, 10);
Rectangle rectangle2 = new Rectangle(7.5, 3.5);
double length1 = rectangle1.getLength();
double width1 = rectangle1.getWidth();
System.out.println("Rectangle 1: Length = " + length1 + ", Width = " + width1);
double length2 = rectangle2.getLength();
double width2 = rectangle2.getWidth();
System.out.println("Rectangle 2: Length = " + length2 + ", Width = " + width2);
double area1 = rectangle1.calculateArea();
double perimeter1 = rectangle1.calculatePerimeter();
System.out.println("Rectangle 1: Area = " + area1 + ", Perimeter = " + perimeter1);
double area2 = rectangle2.calculateArea();
double perimeter2 = rectangle2.calculatePerimeter();
System.out.println("Rectangle 2: Area = " + area2 + ", Perimeter = " + perimeter2);
rectangle1.setLength(8.2);
rectangle1.setWidth(4.6);
area1 = rectangle1.calculateArea();
perimeter1 = rectangle1.calculatePerimeter();
System.out.println("Rectangle 1 (Updated): Area = " + area1 + ", Perimeter = " + perimeter1);
}
Experiment-6
Aim: To write a program using constructors and construction over loading.
Source Code:
public class Rectangle {
private double length;
private double width;
public Rectangle() {
length = 0.0;
width = 0.0;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
public double getLength() {
return length;
public double getWidth() {
return width;
public void setLength(double length) {
this.length = length;
public void setWidth(double width) {
this.width = width;
public double calculateArea() {
return length * width;
}
Output:
public class ConstructorOverloadingProgram {
public static void main(String[] args) {
Rectangle rectangle1 = new Rectangle();
Rectangle rectangle2 = new Rectangle(5.0, 10.0);
double length1 = rectangle1.getLength();
double width1 = rectangle1.getWidth();
System.out.println("Rectangle 1: Length = " + length1 + ", Width = " + width1);
double length2 = rectangle2.getLength();
double width2 = rectangle2.getWidth();
System.out.println("Rectangle 2: Length = " + length2 + ", Width = " + width2);
double area1 = rectangle1.calculateArea();
System.out.println("Rectangle 1: Area = " + area1);
double area2 = rectangle2.calculateArea();
System.out.println("Rectangle 2: Area = " + area2);
rectangle1.setLength(8.2);
rectangle1.setWidth(4.6);
area1 = rectangle1.calculateArea();
System.out.println("Rectangle 1 (Updated): Area = " + area1);
}
Experiment-7
Aim: To write a program on on command line arguments.
Source Code:
import java.io.*;
public class CommandLineFileOperations {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Usage: java CommandLineFileOperations <num1> <num2>");
return;
try {
int num1 = Integer.parseInt(args[0].trim());
int num2 = Integer.parseInt(args[1].trim());
int sum = num1 + num2;
System.out.println("Sum of " + num1 + " and " + num2 + " is: " + sum);
String fileName = "result.txt";
try (FileWriter writer = new FileWriter(fileName)) {
writer.write("Sum of " + num1 + " and " + num2 + " is: " + sum);
System.out.println("Result stored in '" + fileName + "'");
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
System.out.println("Reading from '" + fileName + "':");
reader.lines().forEach(System.out::println);
} catch (NumberFormatException e) {
Output:
System.out.println("Error: Please enter valid integers.");
} catch (IOException e) {
System.out.println("File operation error: " + e.getMessage());
}
Output:
Experiment-8
Aim: To write a program on using concept of overloading methods
Source Code:
public class MethodOverloadingProgram {
public static void main(String[] args) {
printNumber(5);
printNumber(2.5);
printNumber("Ten");
printNumber(3, 4);
public static void printNumber(int num) {
System.out.println("Integer number: " + num);
public static void printNumber(double num) {
System.out.println("Double number: " + num);
public static void printNumber(String num) {
System.out.println("String number: " + num);
public static void printNumber(int num1, int num2) {
int sum = num1 + num2;
System.out.println("Sum of two numbers: " + sum);
}
Output:
Experiment-9
Aim: To write a program on inheritance.
Source Code:
class Vehicle {
protected String brand;
public Vehicle(String brand) {
this.brand = brand;
}
public void honk() {
System.out.println("Honk honk!");
}
}
class Car extends Vehicle {
private String model;
public Car(String brand, String model) {
super(brand);
this.model = model;
}
public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Model: " + model);
}
}
public class InheritanceProgram {
public static void main(String[] args) {
Car car = new Car("Ford", "Mustang");
car.displayInfo();
car.honk();
}
}
Output:
Experiment-10
Aim: To write a program on using the concept of method overriding.
Source Code:
class Animal {
public void makeSound() {
System.out.println("The animal makes a sound");
class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
public class MethodOverridingProgram {
public static void main(String[] args) {
Dog dog = new Dog();
dog.makeSound();
}
Output:
Experiment-11
Aim: To write a program on Creation of packages
Source Code:
//Create a directory structure like this:
mypackage/
MathOperations.java
Main.java
//Save this file inside the mypackage/ directory.
package mypackage;
public class MathOperations {
public int add(int a, int b) {
return a + b;
public int subtract(int a, int b) {
return a - b;
//Save this in the main project directory.
import mypackage.MathOperations;
public class Main {
public static void main(String[] args) {
MathOperations math = new MathOperations();
int sum = math.add(10, 5);
int difference = math.subtract(10, 5);
System.out.println("Sum: " + sum);
System.out.println("Difference: " + difference);
}
Output:
Experiment-12
Aim: To write a program on interfaces.
Source Code:
interface Animal {
void makeSound();}
class Dog implements Animal {
@Override
public void makeSound() {
System.out.println("The dog barks");
class Cat implements Animal {
@Override
public void makeSound() {
System.out.println("The cat meows");
public class InterfaceProgram {
public static void main(String[] args) {
Dog dog = new Dog();
Cat cat = new Cat();
dog.makeSound();
cat.makeSound();
}
Experiment-13
Aim: To write a java program on Collections.
Source Code:
import java.util.*;
public class CollectionsExercise {
public static void main(String[] args) {
// 1. Searching student mark percentage using ArrayList
ArrayList<Student> students = new ArrayList<>();
students.add(new Student(101, "Alice", 87.5));
students.add(new Student(102, "Bob", 78.0));
students.add(new Student(103, "Charlie", 92.3));
int searchPin = 102;
searchStudentByPin(students, searchPin);
// 2. LinkedList operations: Insert, Delete, Update
LinkedList<String> tasks = new LinkedList<>(Arrays.asList("Task1", "Task2", "Task3"));
tasks.add("Task4"); // Insert
tasks.remove("Task2"); // Delete
tasks.set(1, "UpdatedTask3"); // Update
System.out.println("\nUpdated LinkedList: " + tasks);
// 3. Searching in a Hashtable
Hashtable<Integer, String> hashTable = new Hashtable<>();
hashTable.put(1, "Apple");
hashTable.put(2, "Banana");
hashTable.put(3, "Cherry");
int searchKey = 2;
System.out.println("\nSearching for key " + searchKey + ": " + hashTable.get(searchKey));
// 4. Sorting Employee details using HashMap
HashMap<Integer, Employee> employeeMap = new HashMap<>();
employeeMap.put(1001, new Employee(1001, "John", 50000));
employeeMap.put(1002, new Employee(1002, "Jane", 70000));
employeeMap.put(1003, new Employee(1003, "Mike", 60000));
List<Map.Entry<Integer, Employee>> sortedEmployees = new ArrayList<>(employeeMap.entrySet());
sortedEmployees.sort(Comparator.comparing(e -> e.getValue().salary));
System.out.println("\nSorted Employees (by salary):");
for (Map.Entry<Integer, Employee> entry : sortedEmployees) {
System.out.println(entry.getValue());
// Method to search student by PIN in ArrayList
public static void searchStudentByPin(ArrayList<Student> students, int pin) {
for (Student s : students) {
if (s.pin == pin) {
System.out.println("\nStudent Found: " + s);
return;
System.out.println("\nStudent with PIN " + pin + " not found.");
// Student Class for ArrayList
class Student {
int pin;
String name;
Output:
double percentage;
public Student(int pin, String name, double percentage) {
this.pin = pin;
this.name = name;
this.percentage = percentage;
public String toString() {
return "PIN: " + pin + ", Name: " + name + ", Percentage: " + percentage;
// Employee Class for HashMap
class Employee {
int id;
String name;
double salary;
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
public String toString() {
return "ID: " + id + ", Name: " + name + ", Salary: " + salary;
}
Experiment-14.
Aim: To write a java Program on try, catch and finally
Source Code:
import java.util.Scanner;
public class ExceptionHandlingExamples {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 1. Try-Catch-Finally Example
try {
System.out.print("Enter a number: ");
int num = scanner.nextInt();
System.out.println("You entered: " + num);
} catch (Exception e) {
System.out.println("Invalid input! Please enter a number.");
} finally {
System.out.println("This block always executes.\n");
// 2. Multiple Catch Example
try {
int[] numbers = {10, 20, 30};
System.out.print("Enter index to access: ");
int index = scanner.nextInt();
// Prevent division by zero before accessing the index
if (index < 0 || index >= numbers.length) {
throw new ArrayIndexOutOfBoundsException();
}
Output:
int result = numbers[index] / 1; // Changed from `/ 0` to prevent immediate exception
System.out.println("Value: " + result);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds! Please enter a valid index.");
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} catch (Exception e) {
System.out.println("Some other error occurred.");
// 3. Nested Try Example
try {
System.out.println("\nEnter two numbers for division:");
int a = scanner.nextInt();
int b = scanner.nextInt();
try {
int division = a / b;
System.out.println("Result: " + division);
} catch (ArithmeticException e) {
System.out.println("Inner Catch: Division by zero is not allowed.");
} catch (Exception e) {
System.out.println("Outer Catch: Invalid input.");
} finally {
System.out.println("Nested Try example finished.");
scanner.close();
}
Experiment-15
Aim: To write a java Program multithreading
Source Code:
class SingleThread extends Thread {
public void run() {
System.out.println("Single Thread Execution: " + Thread.currentThread().getName());
class MultiThread extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println(Thread.currentThread().getName() + " is running - Count: " + i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println("Thread Interrupted: " + e.getMessage());
class PriorityThread extends Thread {
public PriorityThread(String name) {
super(name);
public void run() {
System.out.println(getName() + " running with priority: " + getPriority());
}
class SharedResource {
private boolean available = false;
synchronized void produce() {
try {
System.out.println("Producing Data...");
available = true;
notify(); // Notify consumer thread
} catch (Exception e) {
System.out.println("Error in Producer: " + e.getMessage());
synchronized void consume() {
try {
while (!available) {
wait(); // Wait until data is produced
System.out.println("Consuming Data...");
available = false;
} catch (InterruptedException e) {
System.out.println("Error in Consumer: " + e.getMessage());
public class MultiThreadingExample {
public static void main(String[] args) {
// 1. Single Thread Example
SingleThread t1 = new SingleThread();
Output:
t1.start();
// 2. Multiple Threads Example
MultiThread t2 = new MultiThread();
MultiThread t3 = new MultiThread();
t2.start();
t3.start();
// 3. Priority Example
PriorityThread p1 = new PriorityThread("Low Priority Thread");
PriorityThread p2 = new PriorityThread("High Priority Thread");
p1.setPriority(Thread.MIN_PRIORITY);
p2.setPriority(Thread.MAX_PRIORITY);
p1.start();
p2.start();
// 4. Inter-Thread Communication
SharedResource resource = new SharedResource();
Thread producer = new Thread(() -> resource.produce(), "Producer");
Thread consumer = new Thread(() -> resource.consume(), "Consumer");
producer.start();
consumer.start();
}
Experiment-16
Aim: To write a java Program on graphics and colors
Source Code:
import java.awt.*;
import javax.swing.*;
public class GraphicsExample extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Set background color
setBackground(Color.WHITE);
// Draw a rectangle
g.setColor(Color.RED);
g.fillRect(50, 50, 100, 50);
// Draw an oval
g.setColor(Color.BLUE);
g.fillOval(200, 50, 100, 50);
// Draw a line
g.setColor(Color.GREEN);
g.drawLine(50, 150, 300, 150);
// Draw a circle
g.setColor(Color.ORANGE);
g.fillOval(100, 200, 50, 50);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Graphics and Colors");
GraphicsExample panel = new GraphicsExample();
frame.add(panel);
frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
Experiment-17
Aim: To write a java Program on AWT controls
Source Code:
import java.awt.*;
import java.awt.event.*;
public class AWTControlsDemo extends Frame implements MouseListener, KeyListener, ItemListener,
ActionListener {
Label mouseLabel, keyLabel, textLabel, checkboxLabel, listLabel;
TextField textField;
Button button;
Checkbox checkbox;
List list;
AWTControlsDemo() {
setTitle("AWT Controls Demo");
setSize(500, 400);
setLayout(null);
// Mouse Label
mouseLabel = new Label("Click Here");
mouseLabel.setBounds(20, 50, 150, 30);
add(mouseLabel);
addMouseListener(this);
// Key Label
keyLabel = new Label("Type here...");
keyLabel.setBounds(20, 90, 150, 30);
add(keyLabel);
// Text Field
textField = new TextField();
textField.setBounds(170, 90, 150, 30);
textField.addKeyListener(this);
add(textField);
// Button
button = new Button("Click Me");
button.setBounds(20, 130, 100, 30);
button.addActionListener(this);
add(button);
// Text Label
textLabel = new Label("");
textLabel.setBounds(140, 130, 200, 30);
add(textLabel);
// Checkbox
checkbox = new Checkbox("Accept Terms");
checkbox.setBounds(20, 170, 120, 30);
checkbox.addItemListener(this);
add(checkbox);
checkboxLabel = new Label("");
checkboxLabel.setBounds(160, 170, 200, 30);
add(checkboxLabel);
// List
list = new List();
list.setBounds(20, 210, 120, 70);
list.add("A");
list.add("B");
list.add("C");
list.addItemListener(this);
add(list);
listLabel = new Label("");
listLabel.setBounds(160, 210, 200, 30);
add(listLabel);
setVisible(true);
@Override
public void mouseClicked(MouseEvent e) {
mouseLabel.setText("Mouse Clicked!");
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
@Override
public void keyTyped(KeyEvent e) {
keyLabel.setText("Typed: " + e.getKeyChar());
Output:
}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {}
@Override
public void actionPerformed(ActionEvent e) {
textLabel.setText("Button clicked!");
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getSource() == checkbox) {
checkboxLabel.setText(checkbox.getState() ? "Checked" : "Unchecked");
if (e.getSource() == list) {
listLabel.setText("Selected: " + list.getSelectedItem());
public static void main(String[] args) {
new AWTControlsDemo();