0% found this document useful (0 votes)
4 views41 pages

JavaLab File (1)

The document contains a series of Java programming experiments, each demonstrating different concepts such as class declaration, method overloading, static variables, inheritance, exception handling, and event handling. Each experiment includes a specific aim and corresponding code examples to illustrate the concepts. The experiments cover a wide range of topics, from basic object-oriented programming principles to file handling and user-defined exceptions.

Uploaded by

megha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views41 pages

JavaLab File (1)

The document contains a series of Java programming experiments, each demonstrating different concepts such as class declaration, method overloading, static variables, inheritance, exception handling, and event handling. Each experiment includes a specific aim and corresponding code examples to illustrate the concepts. The experiments cover a wide range of topics, from basic object-oriented programming principles to file handling and user-defined exceptions.

Uploaded by

megha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Experiment: 1

Aim: Declare a class Rectangle with data members length & breadth and member function Input,
Output and CalcArea.

class Rectangle {
float length;
float breadth;
void Input(float length, float breadth){
[Link] = length;
[Link] = breadth;
}
void Output(){
[Link]("Length = " + length + ", ");
[Link]("Breadth = " + breadth);
}
void CalcArea(){
[Link]("Area = " + (length * breadth));
}
}
public class Main{
public static void main(String[] args) {
Rectangle rect = new Rectangle();
[Link](3,5);
[Link]();
[Link]();
}
}
Experiment: 2
Aim: Demonstrate method overloading to calculate area of square, rectangle, triangle.

import [Link];

public class Main{

public static void area(float s){


[Link]("Square Area = " + (s*s));
}
public static void area(float l, float b){
[Link]("Rectangle Area = " + (l*b));
}
public static void area(float a, float b, float c){
float s = (a+b+c)/2;
float ar = s*(s-a)*(s-b)*(s-c);
[Link]("Triangle Area = " + [Link](ar));
}

public static void main(String[] args) {


area(2);
area(2,3);
area(2,3,4);
}
}
Experiment: 3
Aim: Demonstrate the use of static variable, static method, static block

public class Main {

static int staticVariable = 10;

int instanceVariable;

Main(int instanceVariable) {

[Link] = instanceVariable;
}

public static void staticMethod() {


[Link]("Static variable value: " + staticVariable);
}

public void instanceMethod() {

[Link](" - Static variable value: " + staticVariable);

[Link](" - Instance variable value: " + instanceVariable);


}

static {

[Link]("Static-Block executed!");
}

public static void main(String[] args) {

[Link]();

Main obj1 = new Main(30);

[Link] = 15;

[Link]();

Main obj2 = new Main(40);

[Link]();
}}
Experiment: 4
Aim: WAP to demonstrate the concept of ‘this’

public class Main {


int number;

Main(int number) {
[Link] = number;
}
public void printNumber() {
[Link]("Number: " + [Link]);
}
public void updateNumber(int number) {
[Link] = number;
}
public static void main(String[] args) {
Main obj = new Main(10);
[Link]();
[Link](20);
[Link]();
}
}
Experiment: 5
Aim: write a java program to demonstrate multi-level inheritence and heirarchical inheritance

class superBase{
void superBase_meth(){
[Link]("Super CLass");
}
}
class superDerived extends superBase{
void superDerived_meth(){
[Link]("Super Derived CLass");
}
}

class derived1 extends superDerived{


void derived1_meth(){
[Link]("Derived-1 CLass");
}
}
class derived2 extends superDerived{
void derived2_meth(){
[Link]("Derived-2 CLass");
}
}

public class Main {


public static void main(String[] args) {
derived1 d1 = new derived1();
d1.superBase_meth();
d1.superDerived_meth();
d1.derived1_meth();

derived2 d2 = new derived2();


d2.superBase_meth();
d2.superDerived_meth();
d2.derived2_meth();
}
}
Experiment: 6
Aim: WAP to use super() to invoke base class constructor.

class Animal {
private String name;

Animal(String name) {
[Link] = name;
}

void display() {
[Link]("Animal Name: " + name);
}
}

class Dog extends Animal {


private String breed;

Dog(String name, String breed) {


super(name);
[Link] = breed;
}

void display() {
[Link]();
[Link]("Dog Breed: " + breed);
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog("Max", "Labrador");
[Link]();
}
}
Experiment: 7
Aim: Demonstrate run-time polymorphism.

class Animal {
void makeSound() {
[Link]("Animal is making a sound.");
}}
class Dog extends Animal {
void makeSound() {
[Link]("Dog is barking.");
}}
class Cat extends Animal {
void makeSound() {
[Link]("Cat is meowing.");
}}
public class Main {
public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
[Link]();
[Link]();
}
}
Experiment: 8
Aim: Demonstrate the concept of aggregation.

class Address {
private String street;
private String city;
private String state;

public Address(String street, String city, String state) {


[Link] = street;
[Link] = city;
[Link] = state;
}

public String getStreet() {


return street;
}

public String getCity() {


return city;
}

public String getState() {


return state;
}

public String toString() {


return ("Address{" + "street='" + street + '\'' + ", city='" + city + '\'' + ", state='" + state + '\'' + '}');
}
}
class Employee {
private String name;
private int age;
private Address address;

public Employee(String name, int age, Address address) {


[Link] = name;
[Link] = age;
[Link] = address;
}

public String getName() {


return name;
}

public int getAge() {


return age;
}

public Address getAddress() {


return address;
}

public String toString() {


return ("Employee{" + "name='" + name + '\'' + ", age=" + age + ", address=" + address + '}');
}
}

public class Main {


public static void main(String[] args) {
Address address = new Address("123 Main St", "Cityville", "Stateville");
Employee employee = new Employee("John Doe", 30, address);

[Link](employee);
[Link]("Employee Name: " + [Link]());
[Link]("Employee Age: " + [Link]());
[Link]("Employee Address: " + [Link]());
}
}
Experiment: 9
Aim: Demonstrate abstract class with constructor and ‘final’ method.

abstract class Animal {

private String name;

Animal(String name) {

[Link] = name;
}

public String getName() {

return name;
}

public abstract void makeSound();

public final void sleep() {

[Link](name + " is sleeping.");


}}

class Dog extends Animal {

Dog(String name) {

super(name);
}

public void makeSound() {

[Link]("Dog is barking.");
}}

public class Main {

public static void main(String[] args) {

Dog dog = new Dog("Mr. X");

[Link]("Name: " + [Link]());

[Link]();

[Link]();
}}
Experiment: 10
Aim: Demonstrate two interface have unique methods and same data members.

interface Vehicle {

int MAX_SPEED = 120;

void start();

void stop();

interface Car {

int MAX_SPEED = 90;

void accelerate();

void brake();

class SportsCar implements Vehicle, Car {

int MAX_SPEED = 100;

public void start() {

[Link]("Sports car started.");

public void stop() {

[Link]("Sports car stopped.");

}
public void accelerate() {

[Link]("Sports car accelerated.");

public void brake() {

[Link]("Sports car braked.");

void displayInfo() {

[Link]("Max Speed: " + MAX_SPEED);


}

public class Main {

public static void main(String[] args) {

SportsCar sportsCar = new SportsCar();

[Link]();

[Link]();

[Link]();

[Link]();

[Link]();

}
Experiment: 11
Aim: Write a program to demonstrate checked exception during file handling.

import [Link];

import [Link];

import [Link];

public class Main{

public static void main(String[] args) {

FileReader fileReader = null;


BufferedReader bufferedReader = null;

try {

// Open the file

fileReader = new FileReader("nonexistent_file.txt");

bufferedReader = new BufferedReader(fileReader);

// Read the file line by line

String line;

while ((line = [Link]()) != null) {

[Link](line);

} catch (IOException e) {

// Handle the exception

[Link]("An error occurred while reading the file: " + [Link]());

} finally {

// Close the file resources in the finally block

try {

if (bufferedReader != null) {

[Link]();

}
if (fileReader != null) {

[Link]();

} catch (IOException e) {

[Link]("An error occurred while closing the file: " + [Link]());

}
Experiment: 12
Aim: Write a program to demonstrate unchecked exception.

public class Main {

public static void main(String[] args) {

int[] numbers = {1, 2, 3, 4, 5};

int index = 10;

try {

int result = numbers[index];


[Link]("The value at index " + index + " is: " + result);

} catch (ArrayIndexOutOfBoundsException e) {

[Link]("An error occurred: " + [Link]());

}
Experiment: 13
Aim: Write a program to demonstrate creation of multiple child threads.

public class Main {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {

Thread thread = new Thread(new MyRunnable(i));

[Link]();

static class MyRunnable implements Runnable {

private final int threadNumber;

public MyRunnable(int threadNumber) {

[Link] = threadNumber;

public void run() {

[Link]("Thread " + threadNumber + " is running.");

}
Experiment: 14
Aim: Write a program to use Byte stream class to read from a text file and display the content
on the output screen.

import [Link];

import [Link];

public class Main {

public static void main(String[] args) {

FileInputStream fileInputStream = null;


try {

fileInputStream = new FileInputStream("[Link]");

int byteData;

while ((byteData = [Link]()) != -1) {

[Link]((char) byteData);

} catch (IOException e) {

[Link]("An error occurred while reading the file: " + [Link]());

} finally {

try {

if (fileInputStream != null) {
[Link]();

} catch (IOException e) {

[Link]("An error occurred while closing the file: " + [Link]());

}}
Experiment: 15
Aim: Write a program to demonstrate any event handling.

import [Link].*;

import [Link].*;

import [Link];

import [Link];

public class Main {

public static void main(String[] args) {


// Create the main frame

JFrame frame = new JFrame("Event Handling Example");

[Link](JFrame.EXIT_ON_CLOSE);

// Create a button

JButton button = new JButton("Click Me");

[Link](new ButtonClickListener());

// Add the button to the frame

[Link]().add(button, [Link]);

// Set frame properties and make it visible

[Link](300, 200);

[Link](null); // Center the frame on the screen

[Link](true);

static class ButtonClickListener implements ActionListener {

public void actionPerformed(ActionEvent event) {

[Link](null, "Button Clicked!");

}
}

}
Experiment: 16
Aim: Create a class employee which have name, age and address of employee, include methods
getdata() and showdata(), getdata() takes the input from the user, showdata() display the data in
following format:
Name:
Age:
Address:

import [Link];

class Employee {
private String name;

private int age;

private String address;

public void getData() {

Scanner scanner = new Scanner([Link]);

[Link]("Enter the name: ");

name = [Link]();

[Link]("Enter the age: ");

age = [Link]();

[Link](); // Consume the newline character

[Link]("Enter the address: ");

address = [Link]();

public void showData() {

[Link]("Name: " + name);

[Link]("Age: " + age);

[Link]("Address: " + address);


}

public class Main {

public static void main(String[] args) {

Employee employee = new Employee();

[Link]();

[Link]("\nEmployee Details:\n");

[Link]();

}
Experiment: 17
Aim: Write a Java program to perform basic Calculator operations. Make a menu driven program to
select operation to perform (+ - * / ). Take 2 integers and perform operation as chosen by user.

import [Link];

public class Main {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

int num1, num2;


char operator;

[Link]("Enter the first number: ");

num1 = [Link]();

[Link]("Enter the second number: ");

num2 = [Link]();

[Link]("Select the operation (+, -, *, /): ");

operator = [Link]().charAt(0);

double result = 0.0;

switch (operator) {

case '+':

result = num1 + num2;

break;

case '-':

result = num1 - num2;

break;

case '*':

result = num1 * num2;


break;

case '/':

if (num2 != 0) {

result = (double) num1 / num2;

} else {

[Link]("Error: Division by zero is not allowed.");

[Link](0);

break;

default:
[Link]("Error: Invalid operator.");

[Link](0);

[Link]("Result: " + result);

[Link]();

}
Experiment: 18
Aim: Write a program to make use of BufferedStream to read lines from the keyboard until
'STOP' is typed.

import [Link];

import [Link];

import [Link];

public class Main {

public static void main(String[] args) {


BufferedReader reader = new BufferedReader(new InputStreamReader([Link]));

try {

String line;

while (true) {

line = [Link]();

if ([Link]("STOP")) {

break;

[Link]("You entered: " + line);

}
} catch (IOException e) {

[Link]("An error occurred while reading input: " + [Link]());

} finally {

try {

if (reader != null) {

[Link]();

} catch (IOException e) {

[Link]("An error occurred while closing the reader: " + [Link]());

}
}}
Experiment: 19
Aim: Write a program declaring a Java class called SavingsAccount with members `accountNumber`
and `Balance`. Provide member functions as `depositAmount ()` and `withdrawAmount ()`. If user tries to
withdraw an amount greater than their balance then throw a user-defined exception.

class InsufficientBalanceException extends Exception {

public InsufficientBalanceException(String message) {

super(message);

class SavingsAccount {

private String accountNumber;

private double balance;

public SavingsAccount(String accountNumber, double balance) {

[Link] = accountNumber;

[Link] = balance;

public void depositAmount(double amount) {

balance += amount;
[Link]("Amount deposited successfully.");

public void withdrawAmount(double amount) throws InsufficientBalanceException {

if (amount > balance) {

throw new InsufficientBalanceException("Insufficient balance. Cannot withdraw.");

} else {

balance -= amount;

[Link]("Amount withdrawn successfully.");

}
}

public double getBalance() {

return balance;

public class Main {

public static void main(String[] args) {

SavingsAccount account = new SavingsAccount("1234567890", 1000.0);

try {

[Link](500.0);

[Link](200.0);

[Link](2000.0); // This will throw InsufficientBalanceException

} catch (InsufficientBalanceException e) {

[Link]("Exception: " + [Link]());

[Link]("Account balance: " + [Link]());

}
Experiment: 20
Aim: Write a program creating 2 threads using Runnable interface. Print your name in `run ()`
method of first class and "Hello Java" in `run ()` method of second thread.

class NameThread implements Runnable {

public void run() {

[Link]("Your Name");

class HelloThread implements Runnable {

public void run() {

[Link]("Hello Java");

public class Main {

public static void main(String[] args) {

Thread thread1 = new Thread(new NameThread());

Thread thread2 = new Thread(new HelloThread());

[Link]();

[Link]();

}
Experiment: 21
Aim: Write program that uses swings to display combination of RGB using 3 scrollbars.

import [Link].*;

import [Link].*;

import [Link];

import [Link];

public class Main extends JFrame {

private JScrollBar redScrollBar;


private JScrollBar greenScrollBar;

private JScrollBar blueScrollBar;

private JPanel colorPanel;

Main() {

setTitle("RGB Color Combination");

setSize(400, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());

redScrollBar = new JScrollBar([Link], 0, 0, 0, 255);

greenScrollBar = new JScrollBar([Link], 0, 0, 0, 255);

blueScrollBar = new JScrollBar([Link], 0, 0, 0, 255);

colorPanel = new JPanel();

[Link](new ScrollBarListener());

[Link](new ScrollBarListener());

[Link](new ScrollBarListener());

add(redScrollBar, [Link]);

add(greenScrollBar, [Link]);

add(blueScrollBar, [Link]);

add(colorPanel, [Link]);
setVisible(true);
}

private class ScrollBarListener implements AdjustmentListener {

public void adjustmentValueChanged(AdjustmentEvent e) {

int red = [Link]();

int green = [Link]();

int blue = [Link]();

Color color = new Color(red, green, blue);

[Link](color);

}
}

public static void main(String[] args) {

[Link](new Runnable() {

public void run() {

new Main();

});

}}
Experiment: 22
Aim: Write a swing application that uses atleast 5 swing controls.

import [Link].*;

import [Link].*;

import [Link].*;

public class Main extends JFrame {

private JLabel label;

private JTextField textField;


private JButton button;

private JCheckBox checkBox;

private JComboBox<String> comboBox;

private JTextArea textArea;

Main() {

setTitle("Swing Controls Example");

setSize(400, 300);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new FlowLayout());

label = new JLabel("Enter your name:");

textField = new JTextField(15);

button = new JButton("Submit");

checkBox = new JCheckBox("I agree to the terms and conditions");

comboBox = new JComboBox<>(new String[]{"Option 1", "Option 2", "Option 3"});

textArea = new JTextArea(10, 30);

JScrollPane scrollPane = new JScrollPane(textArea);

[Link](new ButtonClickListener());

add(label);

add(textField);
add(button);

add(checkBox);

add(comboBox);

add(scrollPane);

setVisible(true);
}

private class ButtonClickListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

String name = [Link]();


String agreementStatus = [Link]() ? "agreed" : "not agreed";

String selectedOption = [Link]().toString();

String output = "Name: " + name + "\nAgreement: " + agreementStatus + "\nSelected Option: " +
selectedOption;

[Link](output);

}}

public static void main(String[] args) {

[Link](new Runnable() {

public void run() {

new Main();

});

}}
Experiment: 23
Aim: Write a program to implement border layout using Swing.

import [Link].*;

import [Link].*;

public class Main extends JFrame {

Main() {

setTitle("BorderLayout Example");

setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLayout(new BorderLayout());

JButton btnNorth = new JButton("North");

add(btnNorth, [Link]);

JButton btnSouth = new JButton("South");

add(btnSouth, [Link]);

JButton btnEast = new JButton("East");

add(btnEast, [Link]);

JButton btnWest = new JButton("West");

add(btnWest, [Link]);

JButton btnCenter = new JButton("Center");

add(btnCenter, [Link]);

setVisible(true);

}
public static void main(String[] args) {

[Link](new Runnable() {

public void run() {

new Main();

});

}
Experiment: 24
Aim: Write a java program to insert and update details data in the database.

import [Link].*;

public class Main {

private static final String DB_URL = "jdbc:h2:mem:testdb";

private static final String USERNAME = "sa";

private static final String PASSWORD = "";

public static void main(String[] args) {

try (Connection conn = [Link](DB_URL, USERNAME, PASSWORD)) {

createTable(conn);

insertData(conn, "John Doe", 25, "john@[Link]");

updateData(conn, 1, "Jane Smith", 30, "jane@[Link]");

} catch (SQLException e) {

[Link]();
}

public static void createTable(Connection conn) throws SQLException {

String sql = "CREATE TABLE employees (id INT AUTO_INCREMENT, name VARCHAR(100), age INT, email
VARCHAR(100), PRIMARY KEY (id))";

try (Statement statement = [Link]()) {

[Link](sql);

[Link]("Table created successfully.");


}

public static void insertData(Connection conn, String name, int age, String email) throws SQLException {

String sql = "INSERT INTO employees (name, age, email) VALUES (?, ?, ?)";

try (PreparedStatement statement = [Link](sql)) {


[Link](1, name);

[Link](2, age);

[Link](3, email);

int rowsInserted = [Link]();

if (rowsInserted > 0) {

[Link]("Data inserted successfully.");

}}

public static void updateData(Connection conn, int id, String name, int age, String email) throws SQLException {

String sql = "UPDATE employees SET name = ?, age = ?, email = ? WHERE id = ?";

try (PreparedStatement statement = [Link](sql)) {

[Link](1, name);

[Link](2, age);

[Link](3, email);

[Link](4, id);

int rowsUpdated = [Link]();

if (rowsUpdated > 0) {

[Link]("Data updated successfully.");

}}

}}
Experiment: 25
Aim: Write a java program to retrieve data from database and display it on GUI.

import [Link].*;

public class Main {

private JFrame frame;

private JTextArea outputTextArea;

Main() {
frame = new JFrame("Mock Data GUI");

[Link](JFrame.EXIT_ON_CLOSE);

outputTextArea = new JTextArea(10, 40);

[Link](false);

[Link]().add(new JScrollPane(outputTextArea));

[Link]();

[Link](true);

displayMockData();

private void displayMockData() {

String[] mockData = {

"John Doe, 30, New York",

"Jane Smith, 25, Los Angeles",

"Bob Johnson, 35, Chicago"

};

for (String data : mockData) {


[Link](data + "\n");

public static void main(String[] args) {

[Link](Main::new);

You might also like