You are on page 1of 35

PARV 05016702022

1. Write a program declaring a class Rectangle with data member’s length and
breadth and member functions Input,Output and CalcArea.
CODE :-
import java.util.Scanner;

class Rectangle {
private double length;
private double breadth;

public Rectangle(double length, double breadth) {


this.length = length;
this.breadth = breadth;
}
public Rectangle() {
this.length = 0;
this.breadth = 0;
}

public void Input(double length, double breadth) {


this.length = length;
this.breadth = breadth;
}

public void Output() {


System.out.println("Length: " + length);
System.out.println("Breadth: " + breadth);
}

public double CalcArea() {


return length * breadth;
}
}

public class java_lab_q1


{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter length: ");


double length = sc.nextDouble();

System.out.print("Enter breadth: ");


double breadth = sc.nextDouble();

1
PARV 05016702022

Rectangle rectangle = new Rectangle();


rectangle.Input(length, breadth);

System.out.println("\nRectangle Details:");
rectangle.Output();

System.out.println("Area of Rectangle: " + rectangle.CalcArea());

sc.close();
}
}
OUTPUT:-

2
PARV 05016702022

2. Write a program to demonstrate use of method overloading.


CODE:-
public class MethodOverloading_q2 {

public int add(int a, int b) {


return a + b;
}

public int add(int a, int b, int c) {


return a + b + c;
}

public double add(double a, double b) {


return a + b;
}

public String add(String a, String b) {


return a + b;
}

public static void main(String[] args) {


MethodOverloading_q2 ob = new MethodOverloading_q2();

System.out.println("Sum of 5 and 10 is: " + ob.add(5, 10));

System.out.println("Sum of 5, 10, and 15 is: " + ob.add(5, 10, 15));

System.out.println("Sum of 3.5 and 2.5 is: " + ob.add(3.5, 2.5));

System.out.println("Concatenated string: " + ob.add("Hello", " SIMS"));


}
}
OUTPUT:-

3
PARV 05016702022

3. Write a program to demonstrate the use of static variable ,static method and
static block.
CODE:-
public class Static_q3 {

static int staticVar = 0;

static{

System.out.println("Inside static block.");


staticVar = 10;
}

public static void staticMethod() {


System.out.println("Inside static method.");
System.out.println("Value of staticVar: " + staticVar);
}

public static void main(String[] args) {

System.out.println("Value of staticVar before method call: " + staticVar);

staticMethod();
}
}
OUTPUT:-

4
PARV 05016702022

4. Write a program to demonstrate concept of “this”.


CODE:-

class MyClass {
private int x;

public MyClass(int x) {

this.x = x;
}

public void setX(int x) {

this.x = x;
}
public void displayX() {
System.out.println("Value of x: " + this.x);
}

public void callAnotherMethod() {

this.displayX();
}
}

public class this_keyword_q4 {


public static void main(String[] args) {

MyClass ob = new MyClass(5);

ob.displayX();
ob.setX(10);
ob.displayX();

ob.callAnotherMethod();
}
}
OUTPUT:-

5
PARV 05016702022

5. Write a program to demonstrate multi-level and hierarchical inheritance.


CODE:-
class Animal {
public void eat() {
System.out.println("Animal is eating...");
}
}
class Dog extends Animal {
public void bark() {
System.out.println("Dog is barking...");
}
}
class GermanShepherd extends Dog {
public void guard() {
System.out.println("German Shepherd is guarding...");
}
}
class Cat extends Animal {
public void meow() {
System.out.println("Cat is meowing...");
}
}
public class inheritance_q5 {
public static void main(String[] args) {

Dog dog = new Dog();


GermanShepherd germanShepherd = new GermanShepherd();
Cat cat = new Cat();

System.out.println("Demonstrating multi-level inheritance:");


dog.eat();
dog.bark();
System.out.println();

System.out.println("Demonstrating hierarchical inheritance (Dog):");


dog.eat();
dog.bark();
System.out.println();

System.out.println("Demonstrating hierarchical inheritance (Cat):");


cat.eat();
cat.meow();
}
}

6
PARV 05016702022

OUPUT:-

7
PARV 05016702022

6. Write a program to use super() to invoke base class constructor.

CODE:-
class Vehicle {
private String name;
public Vehicle(String name) {
this.name = name;
System.out.println("Vehicle constructor invoked. Name: " + this.name);
}
public void display() {
System.out.println("Vehicle name: " + name);
}
}
class Car extends Vehicle {
private int maxSpeed;
public Car(String name, int maxSpeed) {
super(name);
this.maxSpeed = maxSpeed;
System.out.println("Car constructor invoked. Max Speed: " + this.maxSpeed);
}
public void display() {
super.display();
System.out.println("Max Speed: " + maxSpeed);
}
}
public class Superkeyword {
public static void main(String[] args) {
Car car = new Car("Toyota", 180);
car.display();
}

8
PARV 05016702022

}
OUTPUT:-

9
PARV 05016702022

7. Write a program to demonstrate run-time polymorphism.


CODE:-

class Employee {

public double calculateSalary() {


return 0.0;
}
}
class FullTimeEmployee extends Employee {
private double monthlySalary;

public FullTimeEmployee(double monthlySalary) {


this.monthlySalary = monthlySalary;
}
@Override
public double calculateSalary() {
return monthlySalary;
}
}

class PartTimeEmployee extends Employee {


private double hourlyRate;
private double hoursWorked;

public PartTimeEmployee(double hourlyRate, double hoursWorked) {


this.hourlyRate = hourlyRate;
this.hoursWorked = hoursWorked;
}

@Override
public double calculateSalary() {
return hourlyRate * hoursWorked;
}
}
public class RunTimePolymorphism {
public static void main(String[] args) {

Employee employee1 = new FullTimeEmployee(60000.0);


Employee employee2 = new PartTimeEmployee(8000.0, 2.0);

System.out.println("Monthly salary of Full Time Employee: " +


employee1.calculateSalary());

10
PARV 05016702022

System.out.println("Weekly salary of Part Time Employee: " +


employee2.calculateSalary());

}
}
OUTPUT:-

11
PARV 05016702022

8. Write a program to demonstrate the concept of aggregation.


CODE:-
import java.util.*;

class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
class Department {
private String name;
private List<Employee> employees;
public Department(String name) {
this.name = name;
this.employees = new ArrayList<>();
}
public void addEmployee(Employee employee) {
employees.add(employee);
}
public void displayEmployees() {
System.out.println("Employees in department " + name + ":");

12
PARV 05016702022

for (Employee employee : employees) {


System.out.println("ID: " + employee.getId() + ", Name: " +
employee.getName());
}
}
}
public class aggregation {
public static void main(String[] args) {
Employee employee1 = new Employee(1, "Sayyam Singhal");
Employee employee2 = new Employee(2, "Anhishak Bhalla");
Department department = new Department("IT");
department.addEmployee(employee1);
department.addEmployee(employee2);
department.displayEmployees();
}
}
OUTPUT:-

13
PARV 05016702022

9. Write a program to demonstrate the concept of abstract class with constructor


and “final” method.

Code:-
abstract class Shape {
String color;
public Shape(String color) {
this.color = color;
}
public abstract double calculateArea();
public final void displayColor() {
System.out.println("Color: " + color);
}
}
class Circle extends Shape {
private double radius;
public Circle(String color, double radius) {
super(color);
this.radius = radius;
}
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
public class Q9 {
public static void main(String[] args) {
Circle circle = new Circle("Red", 5.0);
circle.displayColor();
System.out.println("Area of circle: " + circle.calculateArea());
}

14
PARV 05016702022

}
OUTPUT:-

15
PARV 05016702022

10. Write a program to demonstrate the concept of interface when two


interfaces have unique methods and same data members.
CODE:-
interface Interface1 {
int x = 5;
void method1();
}
interface Interface2 {
int x = 10;
void method2();
}
class MyClass implements Interface1, Interface2 {
@Override
public void method1() {
System.out.println("Method 1 implementation");
}
@Override
public void method2() {
System.out.println("Method 2 implementation");
}
}
public class Interface {
public static void main(String[] args) {
MyClass obj = new MyClass();
System.out.println("Value of x from Interface1: " + Interface1.x);
System.out.println("Value of x from Interface2: " + Interface2.x);
obj.method1();
obj.method2();
}
}

16
PARV 05016702022

OUTPUT:-

17
PARV 05016702022

11. Write a program to demonstrate checked exception during file handling.

CODE:-
import java.io.*;
import java.util.*;
public class CheckedException {
public static void main(String[] args) {
try {
File file = new File("C:\\Users\\GOLU\\OneDrive\\Desktop\\HAALTU\\JAVA
PROGRAMMING\\example01.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String data = scanner.nextLine();
System.out.println(data);
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
e.printStackTrace();
}
}
}
OUTPUT:-
FILE NOT FOUND

18
PARV 05016702022

12. Write a program to demonstrate unchecked.


CODE:-
public class Unchecked{
public static void main(String[] args) {
String str = null;

try {
int length = str.length();
System.out.println("Length of string: " + length);
} catch (NullPointerException e) {

System.out.println("NullPointerException: Attempting to call method on null


object reference");
e.printStackTrace();
}
}
}
OUTPUT:-

19
PARV 05016702022

13. Write a program to demonstrate creation of multiple child threads.


CODE:-

class MyThread extends Thread {


public void run() {
System.out.println(Thread.currentThread().getName() + " is running.");
}
}
public class Q13 {
public static void main(String[] args) {

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


MyThread thread = new MyThread();
thread.setName("Thread " + i);
thread.start();
}
}
}
OUTPUT:-

20
PARV 05016702022

Q 14. Write a program to use Byte stream class to read from a text file and display
the content on the output screen.
CODE:-
import java.io.*;
public class Q14 {
public static void main(String[] args) {
FileInputStream inputStream = null;
try {
inputStream = new
FileInputStream("C:\\Users\\GOLU\\OneDrive\\Desktop\\HAALTU\\JAVA
PROGRAMMING\\example01.txt");
int byteData;
while ((byteData = inputStream.read()) != -1) {
System.out.print((char) byteData);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
OUTPUT:-

21
PARV 05016702022

15. Write a program to demonstrate any event handling.


CODE:-
import java.awt.*;
import java.awt.event.*;
class EventTop extends Frame implements ActionListener {
TextField textField;
EventTop()
{
textField = new TextField();
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);
button.addActionListener(this);
add(textField);
add(button);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
textField.setText("HELLO SIMS!");
}
public static void main(String[] args)
{
new EventTop();
}
} OUTPUT:-

22
PARV 05016702022

16. 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:
CODE:-
import java.util.*;
public class Employee {
private String name;
private int age;
private String address;
public void getdata() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter name: ");
this.name = sc.nextLine();
System.out.print("Enter age: ");
this.age = sc.nextInt();
scanner.nextLine(); // Consume newline
System.out.print("Enter address: ");
this.address = sc.nextLine();
}
public void showdata() {
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
System.out.println("Address: " + this.address);
}
public static void main(String[] args) {
Employee emp = new Employee();
emp.getdata();

23
PARV 05016702022

System.out.println("\nEmployee Details:");
emp.showdata();
}
}
OUTPUT:-

24
PARV 05016702022

17. 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.
CODE:-
import java.util.Scanner;
public class BasicCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int choice;
do {
System.out.println("Menu:");
System.out.println("1. Addition (+)");
System.out.println("2. Subtraction (-)");
System.out.println("3. Multiplication (*)");
System.out.println("4. Division (/)");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch(choice) {
case 1:
performAddition();
break;
case 2:
performSubtraction();
break;
case 3:
performMultiplication();
break;
case 4:
performDivision();

25
PARV 05016702022

break;
case 5:
System.out.println("Exiting program...");
break;
default:
System.out.println("Invalid choice! Please enter a number between 1
and 5.");
}
} while(choice != 5);
scanner.close();
}
public static void performAddition() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
double result = num1 + num2;
System.out.println("Result: " + result);
}
public static void performSubtraction() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
double result = num1 - num2;
System.out.println("Result: " + result);
}
public static void performMultiplication() {

26
PARV 05016702022

Scanner scanner = new Scanner(System.in);


System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
double result = num1 * num2;
System.out.println("Result: " + result);
}
public static void performDivision() {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
if (num2 == 0) {
System.out.println("Error! Division by zero is not allowed.");
} else {
double result = num1 / num2;
System.out.println("Result: " + result);
}
}
}
OUTPUT:-

27
PARV 05016702022

18. Write a program to make use of BufferedStream to read lines from the keyboard
until ‘STOP’ is typed.
CODE:-
import java.io.*;
public class BufferedStreamExample {
public static void main(String[] args) {
BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
String line;
try {
System.out.println("Enter lines (type 'STOP' to end):");
while ((line = reader.readLine()) != null) {
if (line.equals("STOP")) {
break;
}
System.out.println("You entered: " + line);
}
} catch (IOException e) {
System.err.println("Error reading input: " + e.getMessage());
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
System.err.println("Error closing reader: " + e.getMessage());
}
}
}
}

28
PARV 05016702022

OUTPUT:-

29
PARV 05016702022

19. 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 than throw a user – defined execption.
CODE:-
import java.util.Scanner;
class InsufficientBalanceException extends Exception {
public InsufficientBalanceException(String message) {
super(message);
}
}
public class SavingsAccount {
private String accountNumber;
private double balance;
public SavingsAccount(String accountNumber, double initialBalance) {
this.accountNumber = accountNumber;
this.balance = initialBalance;
}
public void depositAmount(double amount) {
balance += amount;
System.out.println("Deposit of " + amount + " successful.");
}
public void withdrawAmount(double amount) throws
InsufficientBalanceException {
if (balance >= amount) {
balance -= amount;
System.out.println("Withdrawal of " + amount + " successful.");
} else {
throw new InsufficientBalanceException("Insufficient funds. Withdrawal
failed.");
}

30
PARV 05016702022

}
public double getBalance() {
return balance;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter account number: ");
String accNumber = scanner.nextLine();
System.out.print("Enter initial balance: ");
double initialBalance = scanner.nextDouble();
SavingsAccount account = new SavingsAccount(accNumber, initialBalance);
int choice;
do {
System.out.println("\nMenu:");
System.out.println("1. Deposit");
System.out.println("2. Withdraw");
System.out.println("3. Check Balance");
System.out.println("4. Exit");
System.out.print("Enter your choice: ");
choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.print("Enter amount to deposit: ");
double depositAmount = scanner.nextDouble();
account.depositAmount(depositAmount);
break;
case 2:
try {
System.out.print("Enter amount to withdraw: ");
double withdrawAmount = scanner.nextDouble();

31
PARV 05016702022

account.withdrawAmount(withdrawAmount);
} catch (InsufficientBalanceException e) {
System.out.println(e.getMessage());
}
break;
case 3:
System.out.println("Current Balance: " + account.getBalance());
break;
case 4:
System.out.println("Exiting program...");
break;
default:
System.out.println("Invalid choice! Please enter a number between 1
and 4.");
}
} while (choice != 4);
scanner.close();
}
}
OUTPUT:-

32
PARV 05016702022

20. 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.
CODE:-
class MyName implements Runnable {
public void run() {
System.out.println("Golu Rayy");
}
}
class HelloJava implements Runnable {
public void run() {
System.out.println("Hello java");
}
}
public class MyThread{
public static void main(String[] args) {

MyName myNameThread = new MyName();


HelloJava helloJavaThread = new HelloJava();
Thread thread1 = new Thread(myNameThread);
Thread thread2 = new Thread(helloJavaThread);
thread1.start();
thread2.start();
}
}
OUTPUT:-

33
PARV 05016702022

34
PARV 05016702022

35

You might also like