Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

Java Lab Report (2)

Uploaded by

tahminatisha777
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Java Lab Report (2)

Uploaded by

tahminatisha777
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 23

Name: MD Ashraful Islam

Id: CS-2203068
Reg. No : 774
Department of Computer Science and Engineering
(CSE)
Encapsulation
1. Create a Java class representing a bank account with private attributes
accountNumber, balance, and ownerName. Implement methods to deposit money,
withdraw money, and display the current balance. Ensure proper
encapsulation.

ANS:
public class BankAccount {
private String accountNumber;
private double balance;
private String ownerName;

public BankAccount(String accountNumber, double balance, String ownerName) {


this.accountNumber = accountNumber;
this.balance = balance;
this.ownerName = ownerName;
}

public void deposit(double amount) {


balance += amount;
}

public void withdraw(double amount) {


if (balance >= amount) {
balance -= amount;
} else {
System.out.println("Insufficient funds");
}
}

public void displayBalance() {


System.out.println("Current balance: " + balance);
}
}

2. Extend the previous BankAccount class to include encapsulated methods to


get and set the ownerName.

Ans:
public String getOwnerName() {
return ownerName;
}

public void setOwnerName(String ownerName) {


this.ownerName = ownerName;
}

3. Create a Person class with private attributes name and age. Implement
encapsulated methods to get and set these attributes.

Ans:
public class Person {
private String name;
private int age;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}
}

4. Create a Person class with private attributes name and age. Implement
encapsulated methods to get and set these attributes.

Ans:
public void setAge(int age) {
if (age >= 0) {
this.age = age;
} else {
System.out.println("Age cannot be negative");
}
}

5. Create a Circle class with private attributes radius and color. Implement
encapsulated methods to calculate the area of the circle and to get and set
the color.

Ans:
public class Circle {
private double radius;
private String color;

public double getArea() {


return Math.PI * radius * radius;
}

public String getColor() {


return color;
}

public void setColor(String color) {


this.color = color;
}
}

6. Extend the Circle class to include a method to calculate the circumference of


the circle.

Ans:
public double getCircumference() {
return 2 * Math.PI * radius;
}

7. Create a Student class with private attributes name, rollNumber, and grade.
Implement encapsulated methods to get and set these attributes.

Ans:
public class Student {
private String name;
private int rollNumber;
private char grade;

8. Extend the Student class to include validation in the setter method for the
grade attribute, ensuring that it can only be set to 'A', 'B', 'C', 'D', or 'F'.

Ans:
public void setGrade(char grade) {
if (grade == 'A' || grade == 'B' || grade == 'C' || grade == 'D' || grade == 'F') {
this.grade = grade;
} else {
System.out.println("Invalid grade");
}
}

9. Create a Book class with private attributes title, author, and year. Implement
encapsulated methods to get and set these attributes.

Ans:
public class Book {
private String title;
private String author;
private int year;

// Getters and setters


}

10. Extend the Book class to include validation in the setter method for the year
attribute, ensuring that it cannot be set to a future year.

Ans:
public void setYear(int year) {
if (year <= 2024) {
this.year = year;
} else {
System.out.println("Invalid year");
}
}

Abstraction

1. Create an abstract class Shape with an abstract method calculateArea().


Implement concrete subclasses Circle and Rectangle that extend Shape and
provide implementations for calculateArea().

Ans:
public abstract class Shape {
public abstract double calculateArea();
}

public class Circle extends Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

public class Rectangle extends Shape {


private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double calculateArea() {
return length * width;
}
}

2. Create an abstract class Animal with abstract methods makeSound() and


move(). Implement concrete subclasses Dog and Bird that extend Animal and
provide implementations for the abstract methods.

Ans:
public abstract class Animal {
public abstract void makeSound();
public abstract void move();
}

public class Dog extends Animal {


@Override
public void makeSound() {
System.out.println("Woof!");
}

@Override
public void move() {
System.out.println("Running");
}
}

public class Bird extends Animal {


@Override
public void makeSound() {
System.out.println("Chirp!");
}

@Override
public void move() {
System.out.println("Flying");
}
}
3. Create an abstract class BankAccount with abstract methods deposit() and
withdraw(). Implement concrete subclasses SavingsAccount and
CheckingAccount that extend BankAccount and provide implementations for the
abstract methods.

Ans:
public abstract class BankAccount {
public abstract void deposit(double amount);
public abstract void withdraw(double amount);
}

public class SavingsAccount extends BankAccount {


@Override
public void deposit(double amount) {
}

@Override
public void withdraw(double amount) {
}
}

public class CheckingAccount extends BankAccount {


@Override
public void deposit(double amount) {
}

@Override
public void withdraw(double amount) {
}
}

4. Create an interface Shape with a method calculateArea(). Implement classes


Circle and Rectangle that implement the Shape interface and provide
implementations for calculateArea().

Ans:
public interface Shape {
double calculateArea();
}
public class Circle implements Shape {
private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}

public class Rectangle implements Shape {


private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double calculateArea() {
return length * width;
}
}

5. Create an interface Animal with methods makeSound() and move(). Implement


classes Dog and Bird that implement the Animal interface and provide
implementations for the methods.

Ans:
public interface Animal {
void makeSound();
void move();
}

public class Dog implements Animal {


@Override
public void makeSound() {
System.out.println("Woof!");
}

@Override
public void move() {
System.out.println("Running");
}
}

public class Bird implements Animal {


@Override
public void makeSound() {
System.out.println("Chirp!");
}

@Override
public void move() {
System.out.println("Flying");
}
}

6. Create an interface BankAccount with methods deposit() and withdraw().


Implement classes SavingsAccount and CheckingAccount that implement the
BankAccount interface and provide implementations for the methods.
Ans:
public interface BankAccount {
void deposit(double amount);
void withdraw(double amount);
}

public class SavingsAccount implements BankAccount {


@Override
public void deposit(double amount) {
}

@Override
public void withdraw(double amount) {
}
}
public class CheckingAccount implements BankAccount {
@Override
public void deposit(double amount) {
}

@Override
public void withdraw(double amount) {
}
}

7. Create an abstract class Employee with abstract methods calculateSalary()


and displayInfo(). Implement concrete subclasses Manager and Developer
that extend Employee and provide implementations for the abstract methods.
Ans:
public abstract class Employee {
public abstract double calculateSalary();
public abstract void displayInfo();
}

public class Manager extends Employee {


@Override
public double calculateSalary() {
}

@Override
public void displayInfo() {
}
}

public class Developer extends Employee {


@Override
public double calculateSalary() {
}

@Override
public void displayInfo() {
}
}
8. Create an interface Vehicle with methods start() and stop(). Implement
classes Car and Motorcycle that implement the Vehicle interface and provide
implementations for the methods.
Ans:
public interface Vehicle {
void start();
void stop();
}

public class Car implements Vehicle {


@Override
public void start() {
}

@Override
public void stop() {
}
}

public class Motorcycle implements Vehicle {


@Override
public void start() {
}

@Override
public void stop() {
}
}

9. Create an abstract class BankAccount with abstract methods deposit() and


withdraw(). Implement classes SavingsAccount and CheckingAccount that
extend BankAccount and provide implementations for the abstract methods.
Ans:
public abstract class BankAccount {
public abstract void deposit(double amount);
public abstract void withdraw(double amount);
}

public class SavingsAccount extends BankAccount {


@Override
public void deposit(double amount) {
}

@Override
public void withdraw(double amount) {
}
}

public class CheckingAccount extends BankAccount {


@Override
public void deposit(double amount) {
}

@Override
public void withdraw(double amount) {
}
}

10. Create an interface Phone with methods call() and sendMessage(). Implement
classes SmartPhone and BasicPhone that implement the Phone interface and
provide implementations for the methods.
Ans:
public interface Phone {
void call(String number);
void sendMessage(String message, String recipient);
}

public class SmartPhone implements Phone {


@Override
public void call(String number) {
}

@Override
public void sendMessage(String message, String recipient) {
}
}

public class BasicPhone implements Phone {


@Override
public void call(String number) {
}
@Override
public void sendMessage(String message, String recipient) {
}
}

Exception Handling

1. Write a Java program to demonstrate handling of


ArrayIndexOutOfBoundsException.
Ans:
public class ArrayIndexExceptionExample {
public static void main(String[] args) {
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out of bound!");
}
}
}

2. Write a Java program to demonstrate handling of NullPointerException.


Ans:
public class NullPointerExceptionExample {
public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("NullPointerException occurred!");
}
}
}
3. Write a Java program to demonstrate handling of ArithmeticException.
Ans:
public class ArithmeticExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException occurred: Division by zero!");
}
}
}

4. Write a Java program to demonstrate handling of NumberFormatException.


Ans:
public class NumberFormatExceptionExample {
public static void main(String[] args) {
try {
String str = "abc";
int num = Integer.parseInt(str);
} catch (NumberFormatException e) {
System.out.println("NumberFormatException occurred: Invalid number
format!");
}
}
}

5. Write a Java program to demonstrate handling of FileNotFoundException.


Ans:
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class FileNotFoundExceptionExample {


public static void main(String[] args) {
try {
File file = new File("nonexistent.txt");
FileReader fr = new FileReader(file);
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException occurred: File not found!");
}
}
}

6. Write a Java program to demonstrate handling of IOException.


Ans:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class IOExceptionExample {


public static void main(String[] args) {
try {
File file = new File("sample.txt");
FileReader fr = new FileReader(file);
fr.close(); } catch (IOException e) {
System.out.println("IOException occurred: Error in file operation!");
}
}
}

7. Write a Java program to demonstrate handling of ClassNotFoundException.


Ans:
public class ClassNotFoundExceptionExample {
public static void main(String[] args) {
try {
Class.forName("nonexistent.Class");
} catch (ClassNotFoundException e) {
System.out.println("ClassNotFoundException occurred: Class not found!");
}
}
}

8. Write a Java program to demonstrate handling of InterruptedException.


Ans:
public class InterruptedExceptionExample {
public static void main(String[] args) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("InterruptedException occurred: Thread interrupted!");
}
}
}

9. Write a Java program to demonstrate handling of


UnsupportedOperationException.
Ans:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UnsupportedOperationExceptionExample {


public static void main(String[] args) {
try {
List<String> list = new ArrayList<>();
list = Collections.unmodifiableList(list);
list.add("Element");
} catch (UnsupportedOperationException e) {
System.out.println("UnsupportedOperationException occurred: Operation not
supported!");
}
}
}

10. Write a Java program to demonstrate handling of StackOverflowError.


Ans:
public class StackOverflowErrorExample {
public static void main(String[] args) {
try {
recursiveMethod(0);
} catch (StackOverflowError e) {
System.out.println("StackOverflowError occurred: Stack overflow!");
}
}

public static void recursiveMethod(int num) {


recursiveMethod(num + 1);
}
}

Polymorphism
1. Create a superclass Shape with a method draw() and two subclasses Circle
and Rectangle that override the draw() method to display "Drawing a Circle"
and "Drawing a Rectangle", respectively.
Ans:
class Shape {
void draw() {
System.out.println("Drawing a Shape");
}
}

class Circle extends Shape {


@Override
void draw() {
System.out.println("Drawing a Circle");
}
}

class Rectangle extends Shape {


@Override
void draw() {
System.out.println("Drawing a Rectangle");
}
}

2. Create a superclass Animal with a method makeSound() and two subclasses


Dog and Cat that override the makeSound() method to display "Woof" and
"Meow", respectively.
Ans:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Woof");
}
}

class Cat extends Animal {


@Override
void makeSound() {
System.out.println("Meow");
}
}

3. Create an interface Shape with a method draw(). Implement two classes


Circle and Rectangle that implement the Shape interface and provide
implementations for the draw() method.
Ans:
interface Shape {
void draw();
}

class Circle implements Shape {


@Override
public void draw() {
System.out.println("Drawing a Circle");
}
}

class Rectangle implements Shape {


@Override
public void draw() {
System.out.println("Drawing a Rectangle");
}
}

4. Create a superclass Vehicle with a method move() and two subclasses Car
and Bike that override the move() method to display "Car is moving" and "Bike
is moving", respectively.
Ans:
class Vehicle {
void move() {
System.out.println("Vehicle is moving");
}
}

class Car extends Vehicle {


@Override
void move() {
System.out.println("Car is moving");
}
}

class Bike extends Vehicle {


@Override
void move() {
System.out.println("Bike is moving");
}
}

5. Create an interface Animal with a method makeSound(). Implement two


classes Dog and Cat that implement the Animal interface and provide
implementations for the makeSound() method.
Ans:
interface Animal {
void makeSound();
}

class Dog implements Animal {


@Override
public void makeSound() {
System.out.println("Woof");
}
}

class Cat implements Animal {


@Override
public void makeSound() {
System.out.println("Meow");
}
}
6. Create a superclass Employee with a method calculateSalary() and two
subclasses Manager and Developer that override the calculateSalary()
method to calculate the salary differently for each subclass.
Ans:
class Employee {
double calculateSalary() {
return 0.0;
}
}

class Manager extends Employee {


@Override
double calculateSalary() {
return 10000.0;
}
}

class Developer extends Employee {


@Override
double calculateSalary() {
return 8000.0;
}
}

7. Create an interface Shape with a method draw(). Implement two classes


Circle and Square that implement the Shape interface and provide
implementations for the draw() method.
Ans:
interface Shape {
void draw();
}

class Circle implements Shape {


@Override
public void draw() {
System.out.println("Drawing a Circle");
}
}
class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Square");
}
}

8. Create a superclass Food with a method eat() and two subclasses Pizza and
Sushi that override the eat() method to display "Eating Pizza" and "Eating
Sushi", respectively.
Ans:
class Food {
void eat() {
System.out.println("Eating Food");
}
}

class Pizza extends Food {


@Override
void eat() {
System.out.println("Eating Pizza");
}
}

class Sushi extends Food {


@Override
void eat() {
System.out.println("Eating Sushi");
}
}

9. Create an interface Instrument with a method play(). Implement two classes


Guitar and Piano that implement the Instrument interface and provide
implementations for the play() method.
Ans:
interface Instrument {
void play();
}

class Guitar implements Instrument {


@Override
public void play() {
System.out.println("Playing Guitar");
}
}

class Piano implements Instrument {


@Override
public void play() {
System.out.println("Playing Piano");
}
}

10. Create a superclass Person with a method displayInfo() and two subclasses
Student and Teacher that override the displayInfo() method to display
information specific to each subclass.
Ans:
class Person {
void displayInfo() {
System.out.println("Person Information");
}
}

class Student extends Person {


@Override
void displayInfo() {
System.out.println("Student Information");
}
}

class Teacher extends Person {


@Override
void displayInfo() {
System.out.println("Teacher Information");
}
}

You might also like