0% found this document useful (0 votes)
36 views32 pages

CO3

Java program

Uploaded by

alainfabo21
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)
36 views32 pages

CO3

Java program

Uploaded by

alainfabo21
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/ 32

EXP3: CLASS AND OBJECTS: STUDY AND IMPLEMENT CLASSES BASED

APPLICATION USING JAVA

Write a program to create a “distance” class with methods where distance is computed
in terms of feet and inches, how to create objects of a class

//23BCP471

class Distance {

int feet;

int inches;

// Constructor

Distance(int feet, int inches) {

this.feet = feet;

this.inches = inches;

// Method to display distance


void displayDistance() {

System.out.println(feet + " feet and " + inches + " inches");

// Clone method

Distance cloneDistance() {

return new Distance(this.feet, this.inches);

}
}

public class DistanceTest {

public static void main(String[] args) {

Distance d1 = new Distance(5, 10); // Create first object


Distance d2 = d1; // Assign reference to another variable
Distance d3 = d1.cloneDistance(); // Create a clone of the first object

d1.displayDistance();

d2.displayDistance();
System.out.print("Clone: ");

d3.displayDistance();

OUTPUT:

Modify the “distance” class by creating constructor for assigning values (feet and inches) to
the distance object. Create another object and assign second object as reference variable to
another object reference variable. Further create a third object which is a clone of the first
object.

//23BCP471

class Demo {

public int publicVar = 100; // Public access

private int privateVar = 200; // Private access

// Public getter

public int getPrivateVar() {

return privateVar;

// Method to modify variable


public void modifyPublicVar(int value) {
publicVar = value;
}

public void modifyPrivateVar(int value) {

privateVar = value;
}

class Test {

static void modifyPrimitive(int x) {

x = 50; // Does not affect the original

static void modifyObject(Demo obj) {

obj.modifyPublicVar(300); // Affects the original

public static void main(String[] args) {

Demo obj = new Demo();

// Public and private access

System.out.println("Public variable: " + obj.publicVar);

System.out.println("Private variable (via getter): " + obj.getPrivateVar());

// Passing by value vs reference

int primitive = 10;

modifyPrimitive(primitive);
System.out.println("After modifying primitive: " + primitive); // No change

modifyObject(obj);
System.out.println("After modifying object: " + obj.publicVar); // Changed

// Use of final keyword

final int finalVar = 100;


// finalVar = 200; // Error: Cannot assign a value to final variable

System.out.println("Final variable: " + finalVar);

Output:

Write a program that implements two constructors in the class. We call the other constructor
using ‘this’ pointer, from the default constructor of the class.
class Demo {

int value;

// Default constructor

Demo() {

this(10); // Invokes the parameterized constructor

System.out.println("Default constructor called.");


}

// Parameterized constructor

Demo(int value) {
this.value = value;
System.out.println("Parameterized constructor called with value: " + value);

public class ConstructorTest {

public static void main(String[] args) {

Demo obj = new Demo(); // Calls the default constructor

Output:

Write a program in Java in which a subclass constructor invokes the constructor of the super
class and instantiate the values.

class Parent {

int parentValue;

// Constructor of superclass

Parent(int value) {

this.parentValue = value;
System.out.println("Parent constructor called with value: " + value);

class Child extends Parent {

int childValue;

// Constructor of subclass
Child(int parentValue, int childValue) {

super(parentValue); // Call superclass constructor

this.childValue = childValue;

System.out.println("Child constructor called with value: " + childValue);


}

public class InheritanceTest {

public static void main(String[] args) {

Child obj = new Child(100, 200); // Instantiate subclass

}
}
Output:

EXP4: INHERITANCE: STUDY AND IMPLEMENT VARIOUS TYPES OF


INHERITANCE IN JAVA.

Write a program in Java to demonstrate single inheritance, multilevel inheritance and


hierarchical inheritance.

class Animal {

void eat() {

System.out.println("This animal eats food.");


}

class Dog extends Animal {


void bark() {

System.out.println("The dog barks.");

public class SingleInheritance {

public static void main(String[] args) {

Dog dog = new Dog();

dog.eat(); // Inherited from Animal

dog.bark();

}
}
Output:

2)

class Animal {

void eat() {

System.out.println("This animal eats food.");


}

class Mammal extends Animal {

void walk() {

System.out.println("This mammal walks.");

}
}
class Dog extends Mammal {

void bark() {

System.out.println("The dog barks.");

}
}

public class MultilevelInheritance {

public static void main(String[] args) {

Dog dog = new Dog();

dog.eat(); // Inherited from Animal

dog.walk(); // Inherited from Mammal


dog.bark();
}

Output:

Java Program to demonstrate the real scenario (e.g., bank) of Java Method Overriding where
three classes are overriding the method of a parent class. Creating a parent class.

class Bank {
double getRateOfInterest() {
return 0; // Base rate

class SBI extends Bank {

@Override
double getRateOfInterest() {
return 5.4;

class ICICI extends Bank {

@Override

double getRateOfInterest() {

return 6.8;

class HDFC extends Bank {


@Override

double getRateOfInterest() {

return 7.1;

public class BankExample {


public static void main(String[] args) {

Bank sbi = new SBI();

Bank icici = new ICICI();

Bank hdfc = new HDFC();

System.out.println("SBI Rate of Interest: " + sbi.getRateOfInterest() + "%");

System.out.println("ICICI Rate of Interest: " + icici.getRateOfInterest() + "%");


System.out.println("HDFC Rate of Interest: " + hdfc.getRateOfInterest() + "%");

}
}
Output:

Write a java program for the use of super and this keyword
class Employee {

String name;

int id;

Employee(String name, int id) {

this.name = name; // Refers to the current object's field

this.id = id;

void display() {

System.out.println("Name: " + this.name + ", ID: " + this.id);

public class ThisKeywordExample {


public static void main(String[] args) {

Employee emp = new Employee("Alice", 101);

emp.display();

Output:
class Animal {

void eat() {

System.out.println("Animal is eating.");

}
}

class Dog extends Animal {

@Override

void eat() {

super.eat(); // Calls the superclass's method

System.out.println("Dog is eating.");
}
}

public class SuperKeywordExample {

public static void main(String[] args) {

Dog dog = new Dog();

dog.eat();

}
}

Output:

Write a java program for the use of final keyword


-FINAL KEYWORD

class Vehicle {

final void start() { // Cannot be overridden

System.out.println("Vehicle is starting.");
}
}

class Car extends Vehicle {

// Attempting to override start() here would result in a compilation error


void drive() {

System.out.println("Car is driving.");

public class FinalKeywordExample {

public static void main(String[] args) {


Car car = new Car();
car.start();

car.drive();

-FINAL VARIABLE

public class FinalVariableExample {

public static void main(String[] args) {


final int speedLimit = 120;

// speedLimit = 140; // Error: Cannot assign a value to final variable

System.out.println("Speed limit: " + speedLimit);

-FINAL CLASS

final class Shape {


void draw() {

System.out.println("Drawing a shape.");
}
}

// class Circle extends Shape { // Error: Cannot inherit from final class

// }

public class FinalClassExample {

public static void main(String[] args) {

Shape shape = new Shape();

shape.draw();

EXP5: POLYMORPHISM: STUDY AND IMPLEMENT VARIOUS TYPES OF


POLYMORPHISM IN JAVA.

Write a program that implements simple example of Runtime Polymorphism with multilevel
inheritance. (e.g., Animal or Shape)

class Animal {

void sound() {

System.out.println("Some generic animal sound");

class Mammal extends Animal {


@Override

void sound() {

System.out.println("Some generic mammal sound");

}
class Dog extends Mammal {

@Override

void sound() {

System.out.println("The dog barks");


}

public class RuntimePolymorphism {

public static void main(String[] args) {

Animal animal; // Reference of parent type

animal = new Animal();


animal.sound(); // Calls Animal's method

animal = new Mammal();

animal.sound(); // Calls Mammal's overridden method

animal = new Dog();

animal.sound(); // Calls Dog's overridden method


}

Output:

Write a program to compute if one string is a rotation of another. For example, pit is rotation
of tip as pit has same character as tip

public class StringRotation {

static boolean isRotation(String s1, String s2) {


// Check if lengths match and s2 is a substring of s1 concatenated with itself
return s1.length() == s2.length() && (s1 + s1).contains(s2);

public static void main(String[] args) {


String str1 = "tip";

String str2 = "pit";

if (isRotation(str1, str2)) {

System.out.println(str2 + " is a rotation of " + str1);

} else {

System.out.println(str2 + " is not a rotation of " + str1);


}
}

Output:

EXP6: STUDY AND IMPLEMENT ABSTRACT CLASS AND INTERFACES IN JAVA


Describe abstract class called Shape which has three subclasses say Triangle, Rectangle,
Circle. Define one method area() in the abstract class and override this area() in these three
subclasses to calculate for specific object i.e. area() of Triangle subclass should calculate area
of triangle etc. Same for Rectangle and Circle.
Write a Java program to create an abstract class Employee with abstract methods
calculateSalary() and displayInfo(). Create subclasses Manager and Programmer that extend
the Employee class and implement the respective methods to calculate salary and display
information for each role.

// Abstract class Employee

abstract class Employee {

protected String name;

protected int id;

protected double baseSalary;

// Constructor
public Employee(String name, int id, double baseSalary) {

this.name = name;

this.id = id;

this.baseSalary = baseSalary;

// Abstract methods
abstract double calculateSalary();

abstract void displayInfo();

// Subclass Manager

class Manager extends Employee {

private double bonus;

// Constructor

public Manager(String name, int id, double baseSalary, double bonus) {


super(name, id, baseSalary);
this.bonus = bonus;

// Implement calculateSalary
@Override

double calculateSalary() {

return baseSalary + bonus;

// Implement displayInfo

@Override
void displayInfo() {
System.out.println("Manager Info:");

System.out.println("Name: " + name + ", ID: " + id + ", Salary: " + calculateSalary());

// Subclass Programmer

class Programmer extends Employee {


private double overtimePay;

// Constructor

public Programmer(String name, int id, double baseSalary, double overtimePay) {

super(name, id, baseSalary);

this.overtimePay = overtimePay;

// Implement calculateSalary
@Override
double calculateSalary() {

return baseSalary + overtimePay;

// Implement displayInfo

@Override

void displayInfo() {

System.out.println("Programmer Info:");

System.out.println("Name: " + name + ", ID: " + id + ", Salary: " + calculateSalary());

// Main class to demonstrate functionality

public class EmployeeExample {

public static void main(String[] args) {

// Create Manager and Programmer objects

Employee manager = new Manager("Alice", 101, 50000, 10000);

Employee programmer = new Programmer("Bob", 102, 40000, 5000);

// Display information and calculate salaries

manager.displayInfo();

programmer.displayInfo();

Output:
EXP7: STUDY AND IMPLEMENT EXCEPTION HANDLING IN JAVA

Write a Java program for try-catch block in exception handling

import java.util.Scanner;

public class ExceptionHandlingExample {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

try {

// Input two numbers


System.out.print("Enter the numerator: ");
int numerator = scanner.nextInt();

System.out.print("Enter the denominator: ");

int denominator = scanner.nextInt();

// Perform division

int result = numerator / denominator;

// Display the result

System.out.println("Result: " + result);

} catch (ArithmeticException e) {

// Handle division by zero

System.out.println("Error: Division by zero is not allowed.");


} catch (Exception e) {

// Handle other unexpected exceptions


System.out.println("Error: An unexpected error occurred - " + e.getMessage());
} finally {

// Always executed

System.out.println("Execution completed.");

scanner.close(); // Close the scanner


}

OUTPUTS:

EXP8: STUDY AND IMPLEMENT FILE HANDLING IN JAVA

Refine the student manager program to manipulate the student information from files by
using the BufferedReader and BufferedWriter CO4 vi. Write a program to manipulate the
information from files by using the Reader and Writer class. Assume suitable data.

import java.io.*;

import java.util.*;

class Student {

private String name;

private int age;


private int rollNumber;
// Constructor

public Student(String name, int age, int rollNumber) {

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

this.rollNumber = rollNumber;

// Getter methods

public String getName() {

return name;
}

public int getAge() {

return age;

public int getRollNumber() {

return rollNumber;
}

// Method to display student information

public void displayInfo() {

System.out.println("Name: " + name + ", Age: " + age + ", Roll Number: " +
rollNumber);

// Method to save student information to file


public void saveToFile(BufferedWriter writer) throws IOException {
writer.write("Name: " + name + ", Age: " + age + ", Roll Number: " + rollNumber);

writer.newLine();

public class StudentManager {

// Method to add student data to a file

public static void addStudentDataToFile(String fileName, List<Student> students) {

try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true))) {

for (Student student : students) {

student.saveToFile(writer);
}
System.out.println("Student data has been added to the file.");

} catch (IOException e) {

System.out.println("An error occurred while writing to the file.");

e.printStackTrace();

// Method to read and display student data from a file

public static void displayStudentDataFromFile(String fileName) {

try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {

String line;

while ((line = reader.readLine()) != null) {

System.out.println(line);

}
} catch (IOException e) {

System.out.println("An error occurred while reading from the file.");


e.printStackTrace();
}

public static void main(String[] args) {


List<Student> students = new ArrayList<>();

students.add(new Student("John Doe", 20, 101));

students.add(new Student("Jane Smith", 22, 102));

students.add(new Student("Emily Davis", 21, 103));

String fileName = "students.txt";

// Add student data to file


addStudentDataToFile(fileName, students);

// Display student data from file

System.out.println("\nDisplaying student data from file:");

displayStudentDataFromFile(fileName);

}
OUTPUT:

File :
EXP9: STUDY AND IMPLEMENT MULTI-THREADED APPLICATION IN JAVA

Write a Java program to demonstrate how to create and start a thread using both theThread
class and the Runnable interface.

// Using Thread class to create a thread


class MyThread extends Thread {

public void run() {

System.out.println("Thread using Thread class is running");

// Using Runnable interface to create a thread

class MyRunnable implements Runnable {


public void run() {

System.out.println("Thread using Runnable interface is running");


}
}

public class ThreadDemo {

public static void main(String[] args) {


// Creating a thread using Thread class

MyThread thread1 = new MyThread();

thread1.start(); // Start the thread

// Creating a thread using Runnable interface

MyRunnable myRunnable = new MyRunnable();

Thread thread2 = new Thread(myRunnable);


thread2.start(); // Start the thread
}

Output:

Write a Java program that illustrates thread synchronization by ensuring multiple threads can
safely access a shared resource without causing data inconsistency.
class Counter {

private int count = 0;

// Synchronized method to ensure thread-safe increment of count

public synchronized void increment() {

count++;

public int getCount() {


return count;

class MyThread extends Thread {

Counter counter;

MyThread(Counter counter) {

this.counter = counter;

public void run() {


// Increment the counter 1000 times

for (int i = 0; i < 1000; i++) {

counter.increment();

public class ThreadSynchronizationDemo {

public static void main(String[] args) {

Counter counter = new Counter();

// Create multiple threads that will increment the counter

MyThread thread1 = new MyThread(counter);

MyThread thread2 = new MyThread(counter);

thread1.start();
thread2.start();
try {

// Wait for both threads to finish

thread1.join();
thread2.join();

} catch (InterruptedException e) {

e.printStackTrace();

// Display the final value of count

System.out.println("Final count value: " + counter.getCount());


}
}

Output:

EXP10: GUI PROGRAMMING USING JAVA APPLET/SWINGS COMPONENTS AND


EVENT HANDLING

import javax.swing.*;

import java.awt.event.*;

public class WindowEventDemo extends JFrame implements WindowListener {

// Constructor to set up the window and add listener

public WindowEventDemo() {

// Set the window title

setTitle("Window Event Handling Demo");


// Set the size of the window

setSize(400, 300);

// Add a window listener to handle window events


addWindowListener(this);

// Set default close operation

setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

// Set window visible

setVisible(true);
}

// Implement the required methods from WindowListener interface

@Override

public void windowOpened(WindowEvent e) {

System.out.println("Window opened.");

@Override

public void windowClosing(WindowEvent e) {

System.out.println("Window is closing.");

// To close the window programmatically, you can use:

// System.exit(0);

dispose(); // or close the window


}

@Override
public void windowClosed(WindowEvent e) {

System.out.println("Window closed.");

@Override

public void windowIconified(WindowEvent e) {

System.out.println("Window minimized.");

@Override

public void windowDeiconified(WindowEvent e) {


System.out.println("Window restored.");
}

@Override

public void windowActivated(WindowEvent e) {

System.out.println("Window activated.");

@Override

public void windowDeactivated(WindowEvent e) {

System.out.println("Window deactivated.");

public static void main(String[] args) {

// Create an instance of WindowEventDemo


new WindowEventDemo();

}
}
OUTPUT:

WINDOWS:

You might also like