0% found this document useful (0 votes)
15 views34 pages

Java Inheritance and Polymorphism Examples

The document outlines various Java programming concepts related to inheritance and polymorphism, including examples of single, multilevel, hierarchical, and method overriding inheritance. It also covers abstract classes, interfaces, and demonstrates runtime polymorphism with dynamic method dispatch. Additionally, it includes a case study for a University Management System showcasing polymorphism through overridden display methods in derived classes.

Uploaded by

Karan Nigal
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)
15 views34 pages

Java Inheritance and Polymorphism Examples

The document outlines various Java programming concepts related to inheritance and polymorphism, including examples of single, multilevel, hierarchical, and method overriding inheritance. It also covers abstract classes, interfaces, and demonstrates runtime polymorphism with dynamic method dispatch. Additionally, it includes a case study for a University Management System showcasing polymorphism through overridden display methods in derived classes.

Uploaded by

Karan Nigal
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

UNIT-III: INHERITANCE AND POLYMORPHISM (6 Hrs)

1. Write a Java program to demonstrate single inheritance.


Create a base class Person and derived class Student.

import [Link];

class Person{
String name;
int age;
double height, weight;

Person(String name, int age, double height, double weight){


[Link] = name;
[Link] = age;
[Link] = height;
[Link] = weight;
}

void printDetails(){
[Link]("Name of the Person: " + name);
[Link]("Age of the Person: " + age);
[Link]("Height of the Person: " + height);
[Link]("Weight of the Person: " + weight);
}
}

class Student extends Person{


String studentId;
String collegeName;

Student(String name, int age, double height, double weight, String studentId, String
collegeName){
super(name, age, height, weight);
[Link] = studentId;
[Link] = collegeName;
}

void printStudentDetails(){
[Link]("Name of the Student: " + name);
[Link]("Age of the Student: " + age);
[Link]("Height of the Student: " + height);
[Link]("Weight of the Student: " + weight);
[Link]("Id of the Student: " + studentId);
[Link]("College Name of the Student: " + collegeName);
}
}

class Main{
public static void main(String[] args){
Student student1 = new Student("Hrishikesh", 19, 5.65, 75.2, "IT65",
"AISSMS IOIT");
[Link]();
[Link]();
}
}
2. Demonstrate multilevel inheritance.
Create classes: Animal → Mammal → Dog.

import [Link];

class Animal {
void eat() {
[Link]("This animal eats food.");
}

void sleep() {
[Link]("This animal sleeps.");
}
}

class Mammal extends Animal {


void walk() {
[Link]("This mammal walks on land.");
}

void giveBirth() {
[Link]("This mammal gives birth to live young.");
}
}

class Dog extends Mammal {


void bark() {
[Link]("The dog barks.");
}

void wagTail() {
[Link]("The dog wags its tail.");
}
}

class Main {
public static void main(String[] args) {
Dog dog = new Dog();

// Calling methods from Dog class


[Link]();
[Link]();

// Calling methods from Mammal class


[Link]();
[Link]();
// Calling methods from Animal class
[Link]();
[Link]();
}
}

3. Use super keyword to access the parent class constructor and method.
Create a program where super is used in constructor chaining.

class Parent {
Parent() {
[Link]("Parent class constructor called");
}

void display() {
[Link]("Method in Parent class");
}
}

class Child extends Parent {


Child() {
super(); // Calls the parent class constructor
[Link]("Child class constructor called");
}

void display() {
[Link](); // Calls the parent class method
[Link]("Method in Child class");
}
}

public class Main {


public static void main(String[] args) {
Child child = new Child();
[Link]();
}
}
4. Write a program showing method overriding.
Show different implementations of a method in parent and child classes.

class Parent {
void display() {
[Link]("This is the display method in the Parent class.");
}

void parentOnlyMethod() {
[Link]("This method is specific to the Parent class.");
}
}

class Child extends Parent {


@Override
void display() {
[Link]("This is the display method in the Child class.");
}

void childOnlyMethod() {
[Link]("This method is specific to the Child class.");
}
}

public class Main {


public static void main(String[] args) {
// Creating an instance of Parent
Parent parent = new Parent();
[Link]("Calling display() on Parent instance:");
[Link]();
[Link]();

[Link]();

// Creating an instance of Child


Child child = new Child();
[Link]("Calling display() on Child instance:");
[Link]();
[Link]();

[Link]();

// Demonstrating polymorphism
Parent parentReference = new Child();
[Link]("Calling display() on Parent reference pointing to Child
instance:");
[Link]();

// Uncommenting the following line will cause a compile-time error


// [Link]();

[Link]();

// Demonstrating instanceof operator


if (parentReference instanceof Child) {
[Link]("parentReference is an instance of Child.");
}

if (parentReference instanceof Parent) {


[Link]("parentReference is also an instance of Parent.");
}

[Link]();

// Casting Parent reference to Child


Child castedChild = (Child) parentReference;
[Link]("Calling childOnlyMethod() after casting:");
[Link]();
}
}
5. Demonstrate runtime polymorphism using dynamic method dispatch.

// Base class

class Animal {

void sound() {

[Link]("Animal makes a sound");

// Derived class 1

class Dog extends Animal {

@Override

void sound() {

[Link]("Dog barks");

// Derived class 2

class Cat extends Animal {

@Override

void sound() {

[Link]("Cat meows");

// Derived class 3

class Cow extends Animal {

@Override

void sound() {
[Link]("Cow moos");

// Main class to demonstrate runtime polymorphism

public class Main {

public static void main(String[] args) {

// Reference of base class pointing to derived class objects

Animal animal;

// Dog object

animal = new Dog();

[Link](); // Calls Dog's sound method

// Cat object

animal = new Cat();

[Link](); // Calls Cat's sound method

// Cow object

animal = new Cow();

[Link](); // Calls Cow's sound method

// Array of Animal references

Animal[] animals = { new Dog(), new Cat(), new Cow() };

[Link]("\nUsing an array of Animal references:");

for (Animal a : animals) {

[Link](); // Calls the respective overridden method

}
6. Create a class hierarchy that includes a base class with a final method.
Show that this method cannot be overridden.

// Base class
class Animal {
// Final method cannot be overridden
public final void eat() {
[Link]("This animal eats food.");
}

// Non-final method can be overridden


public void sound() {
[Link]("This animal makes a sound.");
}
}

// Derived class
class Dog extends Animal {
// Overriding the non-final method
@Override
public void sound() {
[Link]("The dog barks.");
}

// Attempting to override the final method will cause a compilation error


// Uncommenting the below code will result in an error
// @Override
// public void eat() {
// [Link]("The dog eats bones.");
// }
}

// Another derived class


class Cat extends Animal {
// Overriding the non-final method
@Override
public void sound() {
[Link]("The cat meows.");
}
}

public class Main {


public static void main(String[] args) {
Animal genericAnimal = new Animal();
[Link]();
[Link]();

Dog dog = new Dog();


[Link](); // Calls the final method from Animal
[Link](); // Calls the overridden method in Dog

Cat cat = new Cat();


[Link](); // Calls the final method from Animal
[Link](); // Calls the overridden method in Cat
}
}
7. Write a program to demonstrate hierarchical inheritance.

// Base class
class Animal {
void eat() {
[Link]("This animal eats food.");
}

void sleep() {
[Link]("This animal sleeps.");
}
}

// Derived class 1
class Dog extends Animal {
void bark() {
[Link]("The dog barks.");
}
}

// Derived class 2
class Cat extends Animal {
void meow() {
[Link]("The cat meows.");
}
}

// Derived class 3
class Bird extends Animal {
void fly() {
[Link]("The bird flies.");
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Create objects of each derived class
Dog dog = new Dog();
Cat cat = new Cat();
Bird bird = new Bird();

// Demonstrate functionality of Dog


[Link]("Dog:");
[Link]();
[Link]();
[Link]();
// Demonstrate functionality of Cat
[Link]("\nCat:");
[Link]();
[Link]();
[Link]();

// Demonstrate functionality of Bird


[Link]("\nBird:");
[Link]();
[Link]();
[Link]();
}
}
8. Demonstrate the use of final class in Java.
Show how it prevents inheritance.

// Final class declaration


final class FinalClass {
// A method in the final class
public void displayMessage() {
[Link]("This is a method in a final class.");
}
}

// Uncommenting the following code will cause a compilation error


// because FinalClass cannot be extended.
// class SubClass extends FinalClass {
// // Compilation error: Cannot inherit from final 'FinalClass'
// }

public class Main {


public static void main(String[] args) {
// Create an instance of the final class
FinalClass finalClassInstance = new FinalClass();

// Call the method of the final class


[Link]();

[Link]("Inheritance from FinalClass is not allowed.");


}
}
9. Create a class structure using inheritance and calculate the area of different shapes.

// Base class Shape


abstract class Shape {
abstract double calculateArea();
}

// Rectangle class inheriting Shape


class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
[Link] = length;
[Link] = width;
}

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

// Circle class inheriting Shape


class Circle extends Shape {
private double radius;

public Circle(double radius) {


[Link] = radius;
}

@Override
double calculateArea() {
return [Link] * radius * radius;
}
}

// Triangle class inheriting Shape


class Triangle extends Shape {
private double base;
private double height;

public Triangle(double base, double height) {


[Link] = base;
[Link] = height;
}

@Override
double calculateArea() {
return 0.5 * base * height;
}
}

// Main class
public class Main {
public static void main(String[] args) {
Shape rectangle = new Rectangle(5, 10);
Shape circle = new Circle(7);
Shape triangle = new Triangle(6, 8);

[Link]("Area of Rectangle: " + [Link]());


[Link]("Area of Circle: " + [Link]());
[Link]("Area of Triangle: " + [Link]());
}
}
10. Case Study:
Design a program for a University Management System where Person is the base class and
Teacher, Student, and Staff inherit from it. Demonstrate polymorphism using overridden
display() methods.

// Base class
class Person {
String name;
int age;

Person(String name, int age) {


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

void display() {
[Link]("Person Name: " + name + ", Age: " + age);
}
}

// Derived class: Teacher


class Teacher extends Person {
String subject;

Teacher(String name, int age, String subject) {


super(name, age);
[Link] = subject;
}

@Override
void display() {
[Link]("Teacher Name: " + name + ", Age: " + age + ", Subject: "
+ subject);
}
}

// Derived class: Student


class Student extends Person {
String course;

Student(String name, int age, String course) {


super(name, age);
[Link] = course;
}

@Override
void display() {
[Link]("Student Name: " + name + ", Age: " + age + ", Course: " +
course);
}
}

// Derived class: Staff


class Staff extends Person {
String department;

Staff(String name, int age, String department) {


super(name, age);
[Link] = department;
}

@Override
void display() {
[Link]("Staff Name: " + name + ", Age: " + age + ", Department: "
+ department);
}
}

// Main class
public class Main {
public static void main(String[] args) {
Person person1 = new Teacher("Alice", 40, "Mathematics");
Person person2 = new Student("Bob", 20, "Computer Science");
Person person3 = new Staff("Charlie", 35, "Administration");

// Demonstrating polymorphism
[Link]();
[Link]();
[Link]();
}
}
UNIT-IV: ABSTRACT CLASSES AND INTERFACES (6 Hrs)

1. Create an abstract class Shape with abstract method draw() and implement it in Circle and
Rectangle.

// Abstract class Shape


abstract class Shape {
// Abstract method
abstract void draw();
}

// Circle class extending Shape


class Circle extends Shape {
@Override
void draw() {
[Link]("Drawing a Circle");
}
}
// Rectangle class extending Shape
class Rectangle extends Shape {
@Override
void draw() {
[Link]("Drawing a Rectangle");
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Create instances of Circle and Rectangle
Shape circle = new Circle();
Shape rectangle = new Rectangle();

// Call draw method


[Link]();
[Link]();
}
}
2. Define an interface Printable and implement it in two different classes Book and Magazine.

// Define the Printable interface


interface Printable {
void printDetails();
}

// Implement Printable in the Book class


class Book implements Printable {
private String title;
private String author;

public Book(String title, String author) {


[Link] = title;
[Link] = author;
}

@Override
public void printDetails() {
[Link]("Book Title: " + title);
[Link]("Author: " + author);
}
}

// Implement Printable in the Magazine class


class Magazine implements Printable {
private String name;
private int issueNumber;

public Magazine(String name, int issueNumber) {


[Link] = name;
[Link] = issueNumber;
}

@Override
public void printDetails() {
[Link]("Magazine Name: " + name);
[Link]("Issue Number: " + issueNumber);
}
}

// Main class to test the implementation


public class Main {
public static void main(String[] args) {
// Create instances of Book and Magazine
Printable book = new Book("The Great Gatsby", "F. Scott Fitzgerald");
Printable magazine = new Magazine("National Geographic", 202);

// Print details of each


[Link]("Printing Book Details:");
[Link]();

[Link]("\nPrinting Magazine Details:");


[Link]();
}
}
3. Demonstrate multiple interfaces implemented by a single class.

interface Animal {
void eat();
void sleep();
}

interface Bird {
void fly();
void sing();
}

class Bat implements Animal, Bird {


@Override
public void eat() {
[Link]("Bat is eating insects.");
}

@Override
public void sleep() {
[Link]("Bat is sleeping during the day.");
}

@Override
public void fly() {
[Link]("Bat is flying at night.");
}
@Override
public void sing() {
[Link]("Bat is making echolocation sounds.");
}
}

public class Main {


public static void main(String[] args) {
Bat bat = new Bat();

[Link]("As an Animal:");
[Link]();
[Link]();

[Link]("\nAs a Bird:");
[Link]();
[Link]();
}
}
4. Write a program with nested interfaces and implement them.

// File: /d:/Coding/Java/Endsem Practice/[Link]


class Main {
// Outer interface
interface OuterInterface {
void outerMethod();

// Nested interface
interface NestedInterface {
void nestedMethod();
}
}

// Class implementing the outer interface


static class OuterClass implements OuterInterface {
@Override
public void outerMethod() {
[Link]("OuterInterface method implemented in
OuterClass.");
}
}

// Class implementing the nested interface


static class NestedClass implements [Link] {
@Override
public void nestedMethod() {
[Link]("NestedInterface method implemented in
NestedClass.");
}
}
public static void main(String[] args) {
// Using the outer interface implementation
OuterInterface outer = new OuterClass();
[Link]();

// Using the nested interface implementation


[Link] nested = new NestedClass();
[Link]();
}
}
5. Show the use of variables in interfaces (constants by default).

// Interface with constants


interface Constants {
// Variables in interfaces are public, static, and final by default
int MAX_USERS = 100;
String APP_NAME = "MyApplication";
double VERSION = 1.0;

// Abstract method
void displayConstants();
}

// Class implementing the interface


class Application implements Constants {
@Override
public void displayConstants() {
[Link]("Application Name: " + APP_NAME);
[Link]("Maximum Users: " + MAX_USERS);
[Link]("Version: " + VERSION);
}
}

// Another class implementing the interface


class AdminPanel implements Constants {
@Override
public void displayConstants() {
[Link]("Admin Panel for: " + APP_NAME);
[Link]("Supports up to " + MAX_USERS + " users.");
[Link]("Running on version: " + VERSION);
}
}

// Main class
public class Main {
public static void main(String[] args) {
// Create objects of classes implementing the interface
Application app = new Application();
AdminPanel admin = new AdminPanel();

// Display constants using the implemented methods


[Link]("=== Application Info ===");
[Link]();

[Link]("\n=== Admin Panel Info ===");


[Link]();
}
}
6. Write a program where interfaces extend other interfaces.

// Base interface
interface Animal {
void eat();
void sleep();
}

// Extended interface
interface Pet extends Animal {
void play();
}

// Another extended interface


interface WildAnimal extends Animal {
void hunt();
}

// Class implementing Pet interface


class Dog implements Pet {
@Override
public void eat() {
[Link]("Dog is eating.");
}

@Override
public void sleep() {
[Link]("Dog is sleeping.");
}

@Override
public void play() {
[Link]("Dog is playing.");
}
}

// Class implementing WildAnimal interface


class Tiger implements WildAnimal {
@Override
public void eat() {
[Link]("Tiger is eating.");
}

@Override
public void sleep() {
[Link]("Tiger is sleeping.");
}

@Override
public void hunt() {
[Link]("Tiger is hunting.");
}
}

// Main class
public class Main {
public static void main(String[] args) {
Pet myDog = new Dog();
[Link]();
[Link]();
[Link]();

WildAnimal myTiger = new Tiger();


[Link]();
[Link]();
[Link]();
}
}
7. Write a program with an abstract class and a concrete subclass, showing abstract and
concrete methods.

abstract class Animal {


private String name;

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

// Abstract method
public abstract void makeSound();

// Concrete method
public void eat() {
[Link](name + " is eating.");
}

// Getter for name


public String getName() {
return name;
}
}

class Dog extends Animal {


// Constructor
public Dog(String name) {
super(name);
}
// Implementing abstract method
@Override
public void makeSound() {
[Link](getName() + " says: Woof Woof!");
}

// Additional concrete method


public void fetch() {
[Link](getName() + " is fetching the ball.");
}
}

class Cat extends Animal {


// Constructor
public Cat(String name) {
super(name);
}

// Implementing abstract method


@Override
public void makeSound() {
[Link](getName() + " says: Meow!");
}

// Additional concrete method


public void scratch() {
[Link](getName() + " is scratching the furniture.");
}
}

public class Main {


public static void main(String[] args) {
// Create Dog object
Dog dog = new Dog("Buddy");
[Link]();
[Link]();
[Link]();

[Link]();

// Create Cat object


Cat cat = new Cat("Whiskers");
[Link]();
[Link]();
[Link]();
}
}
8. Implement interface methods in a class and use interface reference to call the methods.

// Define the interface


interface Animal {
void eat();
void sleep();
void makeSound();
}

// Implement the interface in a class


class Dog implements Animal {
@Override
public void eat() {
[Link]("The dog is eating.");
}

@Override
public void sleep() {
[Link]("The dog is sleeping.");
}

@Override
public void makeSound() {
[Link]("The dog says: Woof Woof!");
}
}

// Another class implementing the interface


class Cat implements Animal {
@Override
public void eat() {
[Link]("The cat is eating.");
}

@Override
public void sleep() {
[Link]("The cat is sleeping.");
}

@Override
public void makeSound() {
[Link]("The cat says: Meow!");
}
}

// Main class to demonstrate the usage


public class Main {
public static void main(String[] args) {
// Using interface reference for Dog
Animal dog = new Dog();
[Link]("Dog:");
[Link]();
[Link]();
[Link]();
[Link]();

// Using interface reference for Cat


Animal cat = new Cat();
[Link]("Cat:");
[Link]();
[Link]();
[Link]();
}
}
9. Case Study:
Design a banking system where an interface BankOperations has methods like deposit(),
withdraw(), checkBalance() implemented by classes SBI, ICICI, and HDFC.

interface BankOperations {
void deposit(double amount);
void withdraw(double amount);
double checkBalance();
}

class SBI implements BankOperations {


private double balance;

@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("SBI: Deposited " + amount);
} else {
[Link]("SBI: Invalid deposit amount");
}
}

@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("SBI: Withdrawn " + amount);
} else {
[Link]("SBI: Insufficient balance or invalid amount");
}
}

@Override
public double checkBalance() {
return balance;
}
}

class ICICI implements BankOperations {


private double balance;
@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("ICICI: Deposited " + amount);
} else {
[Link]("ICICI: Invalid deposit amount");
}
}

@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("ICICI: Withdrawn " + amount);
} else {
[Link]("ICICI: Insufficient balance or invalid amount");
}
}

@Override
public double checkBalance() {
return balance;
}
}

class HDFC implements BankOperations {


private double balance;

@Override
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
[Link]("HDFC: Deposited " + amount);
} else {
[Link]("HDFC: Invalid deposit amount");
}
}

@Override
public void withdraw(double amount) {
if (amount > 0 && amount <= balance) {
balance -= amount;
[Link]("HDFC: Withdrawn " + amount);
} else {
[Link]("HDFC: Insufficient balance or invalid amount");
}
}

@Override
public double checkBalance() {
return balance;
}
}

public class Main {


public static void main(String[] args) {
BankOperations sbi = new SBI();
[Link](1000);
[Link](500);
[Link]("SBI Balance: " + [Link]());

BankOperations icici = new ICICI();


[Link](2000);
[Link](1000);
[Link]("ICICI Balance: " + [Link]());

BankOperations hdfc = new HDFC();


[Link](3000);
[Link](1500);
[Link]("HDFC Balance: " + [Link]());
}
}
10. Create an abstract class Appliance with an abstract method turnOn(), and implement it in
Fan and Light.

abstract class Appliance {


// Abstract method to be implemented by subclasses
public abstract void turnOn();
}

class Fan extends Appliance {


@Override
public void turnOn() {
[Link]("The fan is now spinning.");
}
}

class Light extends Appliance {


@Override
public void turnOn() {
[Link]("The light is now on.");
}
}

public class Main {


public static void main(String[] args) {
// Create instances of Fan and Light
Appliance fan = new Fan();
Appliance light = new Light();

// Turn on the appliances


[Link]("Turning on the appliances:");
[Link]();
[Link]();
}
}
UNIT-V: EXCEPTION HANDLING (6 Hrs)

1. Write a program to demonstrate the use of try-catch block with ArithmeticException.

public class Main {


public static void main(String[] args) {
try {
// Code that may throw an ArithmeticException
int result = 10 / 0;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
// Handling the exception
[Link]("ArithmeticException caught: Division by zero is
not allowed.");
}
}
}
2. Create a program with multiple catch blocks handling different exceptions.

public class Main {


public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
[Link](numbers[5]); // This will throw
ArrayIndexOutOfBoundsException

int result = 10 / 0; // This will throw ArithmeticException


[Link](result);

} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array index is out of bounds: " +
[Link]());
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero: " + [Link]());
} catch (Exception e) {
[Link]("An unexpected error occurred: " +
[Link]());
}
}
}
3. Demonstrate nested try-catch blocks in a program.

public class Main {


public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
[Link]("Outer try block: Accessing array element...");
try {
int result = numbers[5] / 0; // This will throw an exception
[Link]("Inner try block: Result is " + result);
} catch (ArithmeticException e) {
[Link]("Inner catch block: ArithmeticException
caught - " + [Link]());
}
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Outer catch block:
ArrayIndexOutOfBoundsException caught - " + [Link]());
}
[Link]("Program continues...");
}
}
4. Write a program to create a custom exception class and throw it.

// Custom exception class


class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}

public class Main {


public static void main(String[] args) {
try {
// Simulate a condition to throw the custom exception
throwCustomException(true);
} catch (CustomException e) {
[Link]("Caught Custom Exception: " + [Link]());
}
}

public static void throwCustomException(boolean condition) throws


CustomException {
if (condition) {
throw new CustomException("This is a custom exception!");
}
}
}
5. Show the use of finally block in exception handling.

public class Main {


public static void main(String[] args) {
try {
// Code that may throw an exception
int result = 10 / 0; // This will throw ArithmeticException
[Link]("Result: " + result);
} catch (ArithmeticException e) {
// Handling the exception
[Link]("Exception caught: " + [Link]());
} finally {
// Code in the finally block will always execute
[Link]("Finally block executed.");
}
[Link]("Program continues...");
}
}
6. Write a program to catch an ArrayIndexOutOfBoundsException.

public class Main {


public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
// Attempting to access an invalid index
[Link](numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Caught an ArrayIndexOutOfBoundsException: "
+ [Link]());
}
}
}
7. Handle NumberFormatException using try-catch block.

public class Main {


public static void main(String[] args) {
String invalidNumber = "abc123";

try {
int number = [Link](invalidNumber);
[Link]("Parsed number: " + number);
} catch (NumberFormatException e) {
[Link]("Error: Invalid number format. " +
[Link]());
}
}
}
8. Create a program with exception propagation using throws keyword.

public class Main {

// Method that throws an exception


public static void riskyMethod() throws ArithmeticException {
[Link]("Inside riskyMethod.");
// Deliberately causing an exception
int result = 10 / 0;
}

// Method that propagates the exception


public static void propagateException() throws ArithmeticException {
[Link]("Inside propagateException.");
riskyMethod();
}

public static void main(String[] args) {


try {
propagateException();
} catch (ArithmeticException e) {
[Link]("Exception caught in main: " + [Link]());
}
[Link]("Program continues after exception handling.");
}
}
9. Write a program to handle both IOException and FileNotFoundException.

import [Link].*;

public class Main {


public static void main(String[] args) {
String filePath = "[Link]";

try (BufferedReader reader = new BufferedReader(new FileReader(filePath)))


{
String line;
while ((line = [Link]()) != null) {
[Link](line);
}
} catch (FileNotFoundException e) {
[Link]("File not found: " + [Link]());
} catch (IOException e) {
[Link]("An I/O error occurred: " + [Link]());
}
}
}
10. Case Study:
Create a login system where invalid username or password throws a custom LoginException.

import [Link];

// File: [Link]

// Custom exception class


class LoginException extends Exception {
public LoginException(String message) {
super(message);
}
}

public class Main {


// Hardcoded username and password for simplicity
private static final String USERNAME = "admin";
private static final String PASSWORD = "password123";

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

[Link]("Enter username: ");


String inputUsername = [Link]();

[Link]("Enter password: ");


String inputPassword = [Link]();

try {
login(inputUsername, inputPassword);
[Link]("Login successful!");
} catch (LoginException e) {
[Link]("Login failed: " + [Link]());
}

[Link]();
}

public static void login(String username, String password) throws LoginException {


if (![Link](username)) {
throw new LoginException("Invalid username.");
}
if (![Link](password)) {
throw new LoginException("Invalid password.");
}
}
}
UNIT-VI: GENERIC PROGRAMMING AND COLLECTIONS FRAMEWORK (6 Hrs)

1. Write a generic class that accepts two different types and prints them.

public class Pair<T, U> {


private T first;
private U second;

public Pair(T first, U second) {


[Link] = first;
[Link] = second;
}

public void print() {


[Link]("First: " + first);
[Link]("Second: " + second);
}

public static void main(String[] args) {


Pair<String, Integer> pair = new Pair<>("Hello", 42);
[Link]();
}
}
2. Create a generic method that accepts an array of any type and prints its elements.

public class Main {


public static <T> void printArrayElements(T[] array) {
for (T element : array) {
[Link](element);
}
}

public static void main(String[] args) {


Integer[] intArray = {1, 2, 3, 4, 5};
String[] stringArray = {"Hello", "World", "Java"};

[Link]("Integer Array:");
printArrayElements(intArray);

[Link]("\nString Array:");
printArrayElements(stringArray);
}
}
3. Write a Java program to demonstrate use of ArrayList (add, remove, iterate).

import [Link];

public class Main {


public static void main(String[] args) {
// Create an ArrayList
ArrayList<String> fruits = new ArrayList<>();

// Add elements to the ArrayList


[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Fruits after adding: " + fruits);

// Remove an element from the ArrayList


[Link]("Banana");
[Link]("Fruits after removing Banana: " + fruits);

// Iterate through the ArrayList


[Link]("Iterating through the ArrayList:");
for (String fruit : fruits) {
[Link](fruit);
}
}
}
4. Use a LinkedList to perform insertions and deletions from both ends.

import [Link];

public class Main {


public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();

// Insertions at both ends


[Link](10); // Insert at the beginning
[Link](20); // Insert at the end
[Link](5); // Insert at the beginning
[Link](25); // Insert at the end

[Link]("List after insertions: " + list);

// Deletions from both ends


[Link](); // Remove from the beginning
[Link](); // Remove from the end

[Link]("List after deletions: " + list);


}
}
5. Implement a HashSet to store unique values and demonstrate iteration.

import [Link];

public class Main {


public static void main(String[] args) {
// Create a HashSet to store unique values
HashSet<String> uniqueValues = new HashSet<>();

// Add elements to the HashSet


[Link]("Apple");
[Link]("Banana");
[Link]("Cherry");
[Link]("Apple"); // Duplicate value, will not be added

// Iterate through the HashSet


[Link]("Iterating through the HashSet:");
for (String value : uniqueValues) {
[Link](value);
}
}
}
6. Create a program using TreeSet to store and sort student names.

import [Link];

public class Main {


public static void main(String[] args) {
// Create a TreeSet to store student names
TreeSet<String> studentNames = new TreeSet<>();

// Add student names to the TreeSet


[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
[Link]("Diana");
[Link]("Eve");

// Display the sorted student names


[Link]("Sorted Student Names:");
for (String name : studentNames) {
[Link](name);
}
}
}
7. Use a HashMap to store key-value pairs of student ID and name. Iterate using entry set.

import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
// Create a HashMap to store student ID and name
HashMap<Integer, String> studentMap = new HashMap<>();

// Add some key-value pairs to the HashMap


[Link](101, "Alice");
[Link](102, "Bob");
[Link](103, "Charlie");

// Iterate through the HashMap using entrySet


for ([Link]<Integer, String> entry : [Link]()) {
[Link]("Student ID: " + [Link]() + ", Name: " +
[Link]());
}
}
}
8. Use a Queue interface and implement a simple task queue using LinkedList.

import [Link];
import [Link];

public class Main {


public static void main(String[] args) {
// Create a Queue using LinkedList
Queue<String> taskQueue = new LinkedList<>();

// Add tasks to the queue


[Link]("Task 1: Complete the report");
[Link]("Task 2: Attend the meeting");
[Link]("Task 3: Review the code");

// Process tasks in the queue


[Link]("Processing tasks...");
while (![Link]()) {
String currentTask = [Link](); // Retrieves and removes the
head of the queue
[Link]("Processing: " + currentTask);
}

[Link]("All tasks processed.");


}
}
9. Demonstrate List, Set, and Map interfaces in a single program.

import [Link].*;

public class Main {


public static void main(String[] args) {
// Demonstrating List
List<String> list = new ArrayList<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Apple"); // Allows duplicates
[Link]("List: " + list);

// Demonstrating Set
Set<String> set = new HashSet<>();
[Link]("Apple");
[Link]("Banana");
[Link]("Apple"); // Does not allow duplicates
[Link]("Set: " + set);

// Demonstrating Map
Map<Integer, String> map = new HashMap<>();
[Link](1, "Apple");
[Link](2, "Banana");
[Link](1, "Orange"); // Keys are unique, value for key 1 is replaced
[Link]("Map: " + map);
}
}
10. Case Study:
Design a Library Management System using collections where books are stored in a Map with
book ID as key and book name as value. Allow adding, removing, and displaying all books.

import [Link];
import [Link];
import [Link];

public class Main {


private static Map<Integer, String> library = new HashMap<>();

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);
int choice;

do {
[Link]("\nLibrary Management System");
[Link]("1. Add Book");
[Link]("2. Remove Book");
[Link]("3. Display All Books");
[Link]("4. Exit");
[Link]("Enter your choice: ");
choice = [Link]();
[Link](); // Consume newline

switch (choice) {
case 1:
addBook(scanner);
break;
case 2:
removeBook(scanner);
break;
case 3:
displayBooks();
break;
case 4:
[Link]("Exiting...");
break;
default:
[Link]("Invalid choice. Please try
again.");
}
} while (choice != 4);

[Link]();
}

private static void addBook(Scanner scanner) {


[Link]("Enter Book ID: ");
int bookId = [Link]();
[Link](); // Consume newline
[Link]("Enter Book Name: ");
String bookName = [Link]();

if ([Link](bookId)) {
[Link]("Book ID already exists. Try again.");
} else {
[Link](bookId, bookName);
[Link]("Book added successfully.");
}
}

private static void removeBook(Scanner scanner) {


[Link]("Enter Book ID to remove: ");
int bookId = [Link]();

if ([Link](bookId)) {
[Link](bookId);
[Link]("Book removed successfully.");
} else {
[Link]("Book ID not found.");
}
}
private static void displayBooks() {
if ([Link]()) {
[Link]("No books in the library.");
} else {
[Link]("Books in the Library:");
for ([Link]<Integer, String> entry : [Link]()) {
[Link]("Book ID: " + [Link]() + ", Book
Name: " + [Link]());
}
}
}
}

Common questions

Powered by AI

Immutable classes, whose fields cannot change after the object is created, are essential in scenarios requiring thread-safe objects, such as caching, concurrent execution, and maintaining constant values. In Java, immutable objects simplify synchronization in multi-threaded applications because their state cannot be altered after construction, eliminating read/write conflicts. Designing applications with immutable classes can improve predictability, ease of use, and reliability while reducing the risk of errors caused by mutable state corruption, thus contributing to robust software architecture .

Polymorphism allows methods to be invoked on an object based on the actual runtime type rather than the declared type of the reference, enabling dynamic method dispatch. This is achieved through method overriding where a subclass provides a specific implementation for a method already defined in its superclass. The Java Runtime Environment resolves calls to overridden methods at runtime, allowing for flexible code where behavior can be changed by simply changing the object's instantiated type. This capability is significant as it underpins the principle of substitutability, promoting code reuse and flexibility as new subclasses and methods can be seamlessly integrated into existing code structures .

The 'final' keyword in Java is used to restrict inheritance, method overriding, and constant initialization. A class declared as final cannot be extended, which is useful when creating immutable classes to ensure data integrity, such as the String class in Java. Methods marked with 'final' cannot be overridden, ensuring that critical behavior remains consistent across subclasses. Declaring variables as final means they must be initialized once, allowing them to act as constants. The main implication on class design is the prevention of unintended modifications that can help maintain robustness and security in sensitive components of a software system .

Generic collections enhance type safety by allowing developers to specify the type of objects a collection can hold, thereby preventing runtime type errors such as ClassCastExceptions. This specification occurs at compile-time, allowing the compiler to catch possible type mismatches early in the development process, reducing errors that would otherwise occur during execution. Generics also eliminate the need for casting when retrieving elements from a collection, simplifying the code and further enhancing readability and maintainability .

Runtime polymorphism, achieved through method overriding, allows objects to be treated as instances of their parent class, enabling a program to invoke methods on an object without knowing the object's specific subclass type. This ability enhances extensibility because new subclasses can be added with overridden methods—this approach ensures that existing code can seamlessly work with new types, provided they follow the same interface. This flexibility is crucial for designing systems that can evolve over time without significant restructuring of existing code .

Interface-based inheritance allows for greater flexibility since a class can implement multiple interfaces, thus providing a way to achieve multiple inheritances in Java. This design facilitates loose coupling and better separation of concerns, as an implementing class can provide specific behavior for each interface method independently of other interfaces. In contrast, class-based inheritance is limited by the single-parent tree structure. Therefore, interfaces enable adherence to the design principle of favoring composition over inheritance by allowing shared behavior without a class hierarchy .

TreeSet, a part of Java's collections framework, is a navigable set that uses a Red-Black tree data structure to store elements. It automatically sorts elements in their natural order or according to a specified comparator. This feature is beneficial for applications needing dynamic sets where maintaining order is essential, such as in range queries or constantly updating lists. The underlying tree ensures that operations like add, remove, and search are logarithmic time complexity, providing efficient sorted set functionalities .

Access modifiers like private, protected, and public control the visibility and accessibility of class members, enforcing encapsulation in object-oriented programming. By using private, developers can restrict access to class fields and methods to the class itself, ensuring that the internal state cannot be altered directly from outside. Protected access allows subclasses and classes within the same package to access members. Public access enables members to be accessible from any other class. Together, these modifiers safeguard an object's internal state, reducing code complexity and enhancing security and maintenance by adhering to the principle of information hiding .

In Java, 'throw' is used within a method to explicitly throw an exception, initiated by the developer, as in `throw new CustomException();`. On the other hand, 'throws' is part of a method's signature indicating that the method might throw exceptions of the specified type, allowing them to be propagated to the calling method for handling. These constructs help define error conditions and control the flow of handling exceptions, facilitating flexible and robust error management across different layers of an application .

The 'finally' block in Java ensures that a segment of code runs regardless of whether an exception is thrown in the try block, making it crucial for releasing resources or performing cleanup tasks. Typical use cases include closing database connections, releasing file handles, or freeing up other system resources to avoid resource leaks. The 'finally' block provides a reliable way to ensure that cleanup actions occur even if an error halts the normal flow, helping maintain the application's reliability and robustness .

You might also like