0% found this document useful (0 votes)
24 views28 pages

23cs301 - Oop Ca1 - QB Ans

Kcg

Uploaded by

tanushreev23
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)
24 views28 pages

23cs301 - Oop Ca1 - QB Ans

Kcg

Uploaded by

tanushreev23
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/ 28

23CS301 – Object Oriented Programming

Question Bank and Answer Key


UNIT 1

1.​ i.) Explain OOPS and its feature.(7)

Object-Oriented Programming (OOP):


●​ Definition: OOP is a programming paradigm based on the concept of objects, which contain
data (attributes) and methods (functions) that operate on that data.
●​ Purpose: Provides a way to structure programs for reusability, scalability, and easy
maintenance.
●​ In Java, OOP is integral, enabling modular, scalable, and maintainable code.
●​ OOP supports key principles like encapsulation, inheritance, polymorphism, and abstraction.
●​ Examples: Java, C++, Python (supports OOP).

Main Features of OOP:


1.​ Encapsulation
○​ Binding data and methods into a single unit (class).
○​ Protects data from unauthorized access using access modifiers.
○​ Prevents misuse of internal data.
○​ Fosters maintainable, modular code.

2.​ Abstraction
○​ Hiding internal implementation details and showing only necessary features to the
user.
○​ Achieved using abstract classes and interfaces.
○​ Reduces complexity and improves flexibility, allowing implementation changes
without affecting external clients.

3.​ Inheritance
○​ Mechanism where one class acquires the properties and behavior of another class.
○​ Promotes code reusability.
○​ Avoids redundancy and supports logical organization of related classes.
○​ Enhances flexibility and code reusability—programs can call the same method and
expect different behavior based on the object.

4.​ Polymorphism
○​ Ability to perform a single action in different forms.
○​ Types: Compile-time (method overloading) and Run-time (method overriding).

5.​ Class & Object


○​ Class: Blueprint for creating objects.
i.​ Classes in Java can include data members, methods, constructors, nested
classes, and interfaces.
○​ Object: Instance of a class.
i.​ Objects are created using operations like new in Java, which allocate memory
and initialize instance variables.

Advantages of OOP:
●​ Code reusability
●​ Scalability and easier maintenance
●​ Security via encapsulation
●​ Models real-world scenarios effectively

ii.) Summarize about how classes and objects are created and instantiated.
1.​ Class Creation
○​ A class is a blueprint or template for creating objects.
○​ It defines attributes (variables) and behaviors (methods).
Syntax:​
java​
CopyEdit​
class ClassName {
// attributes
// methods
}
2.​ Object Creation
○​ An object is an instance of a class.
○​ Created using the new keyword, which allocates memory and returns a reference.
Syntax:​
java​
CopyEdit​
ClassName obj = new ClassName();

Example:​
java​
CopyEdit​
class Car {
String brand;
void drive() {
System.out.println("Car is driving");
}
}

public class Main {


public static void main(String[] args) {
Car myCar = new Car(); // object creation
myCar.brand = "Toyota"; // accessing attribute
myCar.drive(); // calling method
}
}

2. Illustrate the control flow statements in Java with suitable examples.

Control flow statements determine the sequence in which statements are executed in a program.
They are classified into Decision-making, Looping, and Jump statements.

1. Decision-Making Statements:
a) if statement
What it does: Executes a block of code if the given condition is true.​
Syntax:
if (condition) {
// statements
}
Example:
if (age >= 18) {
System.out.println("Eligible to vote");
}

b) if-else statement
What it does: Executes one block if condition is true, another if false.​
Syntax:
if (condition) {
// statements if true
} else {
// statements if false
}
Example:
if (marks >= 50)
System.out.println("Pass");
else
System.out.println("Fail");

c) switch statement
What it does: Selects one case to execute from multiple options.​
Syntax:
switch(expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// statements
}
Example:
switch(day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
default: System.out.println("Invalid");
}

2. Looping Statements:
a) for loop
What it does: Repeats code a fixed number of times.​
Syntax:
for(initialization; condition; update) {
// statements
}
Example:
for(int i = 1; i <= 5; i++) {
System.out.println(i);
}
b) while loop
What it does: Repeats code while the condition is true.​
Syntax:
while(condition) {
// statements
}
Example:
int i = 1;
while(i <= 5) {
System.out.println(i);
i++;
}

c) do-while loop
What it does: Executes code at least once, then repeats while condition is true.​
Syntax:
do {
// statements
} while(condition);
Example:
int i = 1;
do {
System.out.println(i);
i++;
} while(i <= 5);

3. Jump Statements
a) break
What it does: Exits from the loop or switch immediately.​
Syntax:
break;
Example:
for(int i = 1; i <= 5; i++) {
if(i == 3) break;
System.out.println(i);
}

b) continue
What it does: Skips the current iteration and moves to the next.​
Syntax:
continue;
Example:
for(int i = 1; i <= 5; i++) {
if(i == 3) continue;
System.out.println(i);
}

c) return
What it does: Exits from a method and optionally returns a value.​
Syntax:
return value; // or just return;
Example:
public int sum(int a, int b) {
return a + b;
}

3. Write a Java program to implement Queue operations.


●​ Queue class contains:
○​ enqueue() → adds an element to the rear.
○​ dequeue() → removes an element from the front.
○​ peek() → shows the front element without removing it.
○​ display() → prints all elements in the queue.
●​ Circular array logic is used to efficiently utilize space.
●​ Menu-driven so you can perform multiple operations interactively.

Program:
import java.util.Scanner;

class Queue {
int front, rear, size;
int capacity;
int[] queue;

// Constructor
Queue(int c) {
capacity = c;
front = rear = size = 0;
queue = new int[capacity];
}

// Enqueue operation
void enqueue(int data) {
if (size == capacity) {
System.out.println("Queue is full");
return;
}
queue[rear] = data;
rear = (rear + 1) % capacity;
size++;
System.out.println(data + " added to queue");
}

// Dequeue operation
void dequeue() {
if (size == 0) {
System.out.println("Queue is empty");
return;
}
System.out.println(queue[front] + " removed from queue");
front = (front + 1) % capacity;
size--;
}

// Peek operation
void peek() {
if (size == 0) {
System.out.println("Queue is empty");
return;
}
System.out.println("Front element: " + queue[front]);
}

// Display operation
void display() {
if (size == 0) {
System.out.println("Queue is empty");
return;
}
System.out.print("Queue elements: ");
for (int i = 0; i < size; i++) {
System.out.print(queue[(front + i) % capacity] + " ");
}
System.out.println();
}
}

public class QueueDemo {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter capacity of queue: ");
int capacity = sc.nextInt();

Queue q = new Queue(capacity);

while (true) {
System.out.println("\nQueue Operations:");
System.out.println("1. Enqueue");
System.out.println("2. Dequeue");
System.out.println("3. Peek");
System.out.println("4. Display");
System.out.println("5. Exit");
System.out.print("Enter your choice: ");
int choice = sc.nextInt();

switch (choice) {
case 1:
System.out.print("Enter value to enqueue: ");
int val = sc.nextInt();
q.enqueue(val);
break;
case 2:
q.dequeue();
break;
case 3:
q.peek();
break;
case 4:
q.display();
break;
case 5:
System.out.println("Exiting...");
sc.close();
return;
default:
System.out.println("Invalid choice");
}
}
}
}

Output:
Queue after enqueue operations: [10, 20, 30]
Dequeued element: 10
Queue after dequeue operation: [20, 30]
Front element: 20
Rear element: 30

4. i. )Develop a simple Java program to sort the given numbers in increasing order using
Insertion Sort. (7)

import java.util.Scanner;
public class InsertionSortExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

System.out.print("Enter number of elements: ");


int n = sc.nextInt();

int arr[] = new int[n]; // array declaration with n elements


System.out.println("Enter " + n + " numbers:");
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}

System.out.println("\nOriginal Array:");
displayArray(arr);

// Insertion Sort
for (int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;

// Shift elements greater than key


while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}

System.out.println("\nSorted Array (Increasing Order):");


displayArray(arr);

sc.close();
}

// Method to display array


public static void displayArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}

Output:
Enter number of elements: 6
Enter 6 numbers:
529156

Original Array:
529156

Sorted Array (Increasing Order):


125569

ii.) Explain the structure of the Java Program with an example. (6)

A Java program generally has these parts:


1.​ Package Declaration (optional)​
Declares the package name if the class belongs to a package.​
package mypackage;

2.​ Import Statements (optional)​


Imports built-in or user-defined classes from other packages.​
import java.util.Scanner;

3.​ Class Definition​


Every Java program must have at least one class, and the file name should match the class
name.​
public class MyProgram {}

4.​ Main Method​


The entry point of the program — execution starts from here.
public static void main(String[] args) {
// code goes here
}

5.​ Statements​
The actual logic of the program inside the main method.​

6.​ Closing Braces​


To end the main method and the class.

Example Java Program


package mypackage; // 1. Package declaration (optional)
import java.util.Scanner; // 2. Import statement (optional)

public class MyProgram { // 3. Class definition


public static void main(String[] args) { // 4. Main method
Scanner sc = new Scanner(System.in); // 5. Statements
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello, " + name + "!");
} // end of main method
} // end of class

●​ Package declaration – optional, for organizing classes.


●​ Import statements – optional, to use built-in or custom classes.
●​ Class definition – must match file name.
●​ Main method – entry point of execution.
●​ Statements – program logic.
●​ Proper closing braces.

5. (i) Explain Java Development Tool kit and Illustrate the working principles of Java Virtual
Machine. (8)

Java Development Kit & JVM Working Principles:


Java Development Kit (JDK)
●​ Definition: A complete software package for developing Java applications.
●​ Main Components:
1.​ Compiler (javac) – Converts .java files to bytecode .class files.
2.​ Java Runtime Environment (JRE) – Provides JVM + core libraries to run programs.
3.​ Development Tools – javadoc, debugger, javap, etc.
●​ Purpose: Enables coding, compiling, and debugging of Java programs. Without JDK, you
cannot create Java applications.

Java Virtual Machine (JVM) – Working Principle


●​ JVM runs Java bytecode and makes Java platform-independent.
●​ Steps inside JVM:
1.​ Class Loader – Loads .class files into memory.
2.​ Bytecode Verifier – Ensures safety and correctness of bytecode.
3.​ Interpreter / JIT Compiler – Converts bytecode into native machine code.
4.​ Execution Engine – Runs the native code to produce output.​
Illustration:

(ii) Execution Process of a Java Program (5 marks)

Definition: The step-by-step procedure from writing Java code to getting the output.
Steps:
1.​ Write Source Code – Create a .java file using a text editor or IDE.
2.​ Compile – Use javac to convert source code into bytecode .class.
3.​ Load Class – JVM Class Loader loads the compiled .class file.
4.​ Verify – Bytecode Verifier checks code safety and validity.
5.​ Execute – JVM Interpreter/JIT translates bytecode into native code and runs it.

Simplified Flow:
Write Code (.java)

javac Compiler

Bytecode (.class)

JVM Loads + Verifies

Interpreter/JIT

Output

6. Explain various operators in java with an example program (13)

public class OperatorsExample {


public static void main(String[] args) {
int a = 10, b = 3;

// Arithmetic
System.out.println("Arithmetic:");
System.out.println(a + b); // Addition
System.out.println(a - b); // Subtraction
System.out.println(a * b); // Multiplication
System.out.println(a / b); // Division
System.out.println(a % b); // Modulus

// Relational
System.out.println("\nRelational:");
System.out.println(a > b); // Greater than
System.out.println(a == b); // Equal to

// Logical
System.out.println("\nLogical:");
System.out.println(a > b && b > 0); // AND
System.out.println(a < b || b > 0); // OR
System.out.println(!(a > b)); // NOT

// Assignment
System.out.println("\nAssignment:");
int x = 5;
x += 3; // x = x + 3
System.out.println(x);
x *= 2; // x = x * 2
System.out.println(x);

// Unary
System.out.println("\nUnary:");
int y = 5;
System.out.println(++y); // Pre-increment
System.out.println(y--); // Post-decrement

// Ternary
System.out.println("\nTernary:");
String result = (a > b) ? "A is greater" : "B is greater";
System.out.println(result);

// Bitwise
System.out.println("\nBitwise:");
int p = 5, q = 3;
System.out.println(p & q); // AND
System.out.println(p | q); // OR
System.out.println(p ^ q); // XOR
System.out.println(p << 1); // Left shift
System.out.println(p >> 1); // Right shift
}
}

Output:
Arithmetic:
13
7
30
3
1

Relational:
true
false
Logical:
true
true
false

Assignment:
8
16

Unary:
6
6

Ternary:
A is greater

Bitwise:
1
7
6
10
2

7. Implement STACK operations using Java programs with sample output.

import java.util.Scanner;

class Stack {
int top;
int maxSize;
int[] stackArray;

// Constructor
Stack(int size) {
maxSize = size;
stackArray = new int[maxSize];
top = -1;
}

// Push operation
void push(int item) {
if (top == maxSize - 1) {
System.out.println("Stack Overflow! Cannot push " + item);
} else {
stackArray[++top] = item;
System.out.println(item + " pushed into stack.");
}
}

// Pop operation
void pop() {
if (top == -1) {
System.out.println("Stack Underflow! Cannot pop.");
} else {
System.out.println(stackArray[top--] + " popped from stack.");
}
}

// Peek operation
void peek() {
if (top == -1) {
System.out.println("Stack is empty!");
} else {
System.out.println("Top element is: " + stackArray[top]);
}
}

// Display stack
void display() {
if (top == -1) {
System.out.println("Stack is empty!");
} else {
System.out.print("Stack elements: ");
for (int i = top; i >= 0; i--) {
System.out.print(stackArray[i] + " ");
}
System.out.println();
}
}
}

public class StackOperations {


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

while (true) {
System.out.println("\n--- Stack Menu ---");
System.out.println("1. Push");
System.out.println("2. Pop");
System.out.println("3. Peek");
System.out.println("4. Display");
System.out.println("5. Exit");
System.out.print("Enter choice: ");
int choice = sc.nextInt();

switch (choice) {
case 1:
System.out.print("Enter value to push: ");
int val = sc.nextInt();
stack.push(val);
break;
case 2:
stack.pop();
break;
case 3:
stack.peek();
break;
case 4:
stack.display();
break;
case 5:
System.out.println("Exiting...");
sc.close();
return;
default:
System.out.println("Invalid choice!");
}
}
}
}

Output:
--- Stack Menu ---
1. Push
2. Pop
3. Peek
4. Display
5. Exit
Enter choice: 1
Enter value to push: 10
10 pushed into stack.

--- Stack Menu ---


Enter choice: 1
Enter value to push: 20
20 pushed into stack.

--- Stack Menu ---


Enter choice: 4
Stack elements: 20 10

--- Stack Menu ---


Enter choice: 3
Top element is: 20

--- Stack Menu ---


Enter choice: 2
20 popped from stack.

--- Stack Menu ---


Enter choice: 4
Stack elements: 10

--- Stack Menu ---


Enter choice: 5
Exiting…

8. Explain default constructor and no-argument constructor with example.

1. Default Constructor
●​ A constructor that Java provides automatically if no constructors are explicitly defined in the
class.
○​ It takes no arguments.
○​ It initializes instance variables to their default values (e.g., 0 for int, null for objects,
false for boolean).
○​ You don’t need to write it — Java creates it for you automatically.​

Example:
class Student {
int rollNo;
String name;

// No constructor defined, so Java provides a default constructor


void display() {
System.out.println("Roll No: " + rollNo + ", Name: " + name);
}
}

public class DefaultConstructorExample {


public static void main(String[] args) {
Student s1 = new Student(); // Default constructor is called
s1.display(); // Outputs default values: 0, null
}
}

Output:
Roll No: 0, Name: null
2. No-Argument Constructor
●​ A constructor that you define explicitly with no parameters.
○​ Unlike the default constructor, you can initialize variables with specific values.
○​ Still has no arguments.​

Example:
class Student {
int rollNo;
String name;

// User-defined no-argument constructor


Student() {
rollNo = 1;
name = "John";
}
void display() {
System.out.println("Roll No: " + rollNo + ", Name: " + name);
}
}

public class NoArgumentConstructorExample {


public static void main(String[] args) {
Student s1 = new Student(); // Calls our no-argument constructor
s1.display(); // Outputs initialized values
}
}

Output:
Roll No: 1, Name: John

9. Write a Java program to create a class called Account with instance variables
accountNumber and balance. Implement a parameterized constructor that
initializes these variables with validation:
●​ accountNumber should be non-null and non-empty.
●​ balance should be non-negative.
●​ Print an error message if the validation fails.

class Account {
private String accountNumber;
private double balance;

// Parameterized constructor with validation


public Account(String accountNumber, double balance) {
if (accountNumber == null || accountNumber.trim().isEmpty()) {
System.out.println("Error: Account number cannot be null or empty.");
return;
}
if (balance < 0) {
System.out.println("Error: Balance cannot be negative.");
return;
}
this.accountNumber = accountNumber;
this.balance = balance;
System.out.println("Account created successfully!");
}

// Method to display account details


public void displayAccountDetails() {
if (accountNumber != null && !accountNumber.trim().isEmpty() && balance
>= 0) {
System.out.println("Account Number: " + accountNumber);
System.out.println("Balance: " + balance);
}
}
}
// Main class to test Account
public class Main {
public static void main(String[] args) {
// Valid account
Account acc1 = new Account("ACC12345", 5000);
acc1.displayAccountDetails();

System.out.println();
Account acc2 = new Account("", 3000);

System.out.println();
// Negative balance
Account acc3 = new Account("ACC98765", -1000);
}
}
Output:
Account created successfully!
Account Number: ACC12345
Balance: 5000.0

Error: Account number cannot be null or empty.

Error: Balance cannot be negative.


UNIT 2

1.​ i.) Explain in detail about inheritance with a simple program. (6)
Definition:​
Inheritance is an object-oriented programming feature that allows one class (child/subclass) to
acquire the properties and behaviors (fields and methods) of another class (parent/superclass). It
promotes code reusability and method overriding.
Types of Inheritance in Java:
1.​ Single Inheritance – One class inherits another.
2.​ Multilevel Inheritance – A class inherits from another, which itself inherits from another.
3.​ Hierarchical Inheritance – Multiple classes inherit from one superclass.​
(Note: Java does not support multiple inheritance with classes, but it is possible with
interfaces.)
Syntax:
class Parent {
// parent class members
}

class Child extends Parent {


// child class members
}

Example:
// Parent Class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Child Class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

// Main Class
public class InheritanceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.eat(); // Inherited method
myDog.bark(); // Child's own method
}
}

Sample Output:
This animal eats food.
The dog barks.
●​ extends keyword is used for inheritance.
●​ Child class gets all non-private members of the parent.
●​ Helps avoid code duplication.

ii.) Explain the use of super ,this keywords in Java with an example.(7)
1. this keyword
●​ Refers to the current object of a class.
●​ Used to differentiate between instance variables and parameters when they have the same
name.
●​ Can be used to:
○​ Call another constructor in the same class (this()).
○​ Pass the current object as an argument.
○​ Access the current object’s methods and fields.​

Syntax:
this.variableName; // Access instance variable
this.methodName(); // Call current class method
this(); // Call another constructor

2. super keyword
●​ Refers to the parent class (superclass) object.
●​ Used to:
○​ Call the parent class constructor (super()).
○​ Access parent class variables or methods that are overridden.​

Syntax:
super.variableName; // Access parent class variable
super.methodName(); // Call parent class method
super(); // Call parent class constructor

Example Program
// Parent class
class Animal {
String name = "Animal";

Animal() {
System.out.println("Animal Constructor");
}

void display() {
System.out.println("This is an animal");
}
}

// Child class
class Dog extends Animal {
String name = "Dog";

Dog() {
super(); // Calls Animal's constructor
System.out.println("Dog Constructor");
}
void showNames(String name) {
System.out.println("Local variable: " + name); // Local variable
System.out.println("Instance variable: " + this.name); // Dog's instance variable
System.out.println("Parent variable: " + super.name); // Animal's variable
}

void display() {
super.display(); // Calls Animal's method
System.out.println("This is a dog");
}
}

// Main class
public class SuperThisExample {
public static void main(String[] args) {
Dog d = new Dog();
d.showNames("Puppy");
d.display();
}
}
Sample Output
Animal Constructor
Dog Constructor
Local variable: Puppy
Instance variable: Dog
Parent variable: Animal
This is an animal
This is a dog

2. Explain in detail about single inheritance ,multilevel inheritance in java with examples for
each type. (13)
1. Single Inheritance
Single inheritance occurs when a child class inherits properties and methods from a single parent
class. This helps in code reusability and maintaining a hierarchical structure.
Example: Single Inheritance
// Parent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Child class inherits Animal


class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

public class SingleInheritanceExample {


public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // Inherited method
d.bark(); // Child class method
}
}

Sample Output:
This animal eats food.
The dog barks.

2. Multilevel Inheritance
Multilevel inheritance is when a class is derived from a child class, making a chain of inheritance.​
In other words, a class inherits from another class, which itself is inherited from a different class.
Example: Multilevel Inheritance
// Grandparent class
class Animal {
void eat() {
System.out.println("This animal eats food.");
}
}

// Parent class
class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}

// Child class
class Puppy extends Dog {
void weep() {
System.out.println("The puppy is weeping.");
}
}

public class MultilevelInheritanceExample {


public static void main(String[] args) {
Puppy p = new Puppy();
p.eat(); // From Animal
p.bark(); // From Dog
p.weep(); // From Puppy
}
}

Sample Output:
This animal eats food.
The dog barks.
The puppy is weeping.
3. Describe in brief about object class and its methods in Java with suitable examples.

●​ In Java, the Object class is the parent (superclass) of all classes. Every class in Java directly
or indirectly inherits from the Object class.
●​ Package: java.lang (import not required).
●​ Purpose:​
It provides default methods that every Java object can use, such as comparison, cloning,
string representation, etc.​

Common Methods of Object Class


Method Description Example Use

public String toString() Returns a string representation Printing an object directly.


of the object.

public boolean Compare two objects for Checking if two objects


equals(Object obj) equality. have the same data.

protected Object Creates and returns a copy of Duplicating an object.


clone() the object.

public int hashCode() Returns hash code value of the Used in hashing-based
object. collections like HashMap.

protected void Called by the Garbage Collector Resource cleanup.


finalize() before the object is destroyed.

public Class<?> Returns the runtime class of the Reflection purposes.


getClass() object.

Example Program
class Student {
String name;
int rollNo;

Student(String name, int rollNo) {


this.name = name;
this.rollNo = rollNo;
}

// Overriding toString() method


public String toString() {
return "Name: " + name + ", Roll No: " + rollNo;
}

// Overriding equals() method


public boolean equals(Object obj) {
Student s = (Student) obj;
return this.rollNo == s.rollNo;
}
}
public class ObjectClassExample {
public static void main(String[] args) {
Student s1 = new Student("Rahul", 101);
Student s2 = new Student("Rahul", 101);
Student s3 = new Student("Priya", 102);

// Using toString()
System.out.println(s1.toString());

// Using equals()
System.out.println("s1 equals s2? " + s1.equals(s2)); // true
System.out.println("s1 equals s3? " + s1.equals(s3)); // false

// Using getClass()
System.out.println("Class of s1: " + s1.getClass());
}
}

Output:
Name: Rahul, Roll No: 101
s1 equals s2? true
s1 equals s3? false
Class of s1: class Student

4. Write a Java program to create a class called Shape with a method called
getArea(). Create a subclass called Rectangle that overrides the getArea()
method to calculate the area of a rectangle.

class Shape {
// Method to get area
public double getArea() {
return 0; // Default implementation
}
}

// Subclass Rectangle
class Rectangle extends Shape {
double length;
double width;

// Constructor
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}

// Overriding getArea() method


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

public class Main {


public static void main(String[] args) {
Rectangle rect = new Rectangle(5, 3);
System.out.println("Area of Rectangle: " + rect.getArea());
}
}

Output:
Area of Rectangle: 15.0

5. Explain how packages are imported in java with an example.


In Java, a package is like a folder that groups related classes, interfaces, and sub-packages together.​
They are mainly used to:
●​ Organize code so it’s easy to maintain.
●​ Avoid name conflicts between classes with the same name.
●​ Provide access control (public, protected, etc.).
●​ Reuse code from built-in or user-defined packages.

Types of Packages
1.​ Built-in Packages – Provided by Java, such as:
○​ java.util (utility classes like ArrayList, Date)
○​ java.io (input/output classes like File, BufferedReader)
2.​ User-defined Packages – Created by programmers to organize their own classes.

Example of using a built-in package:


import java.util.Scanner;

public class PackageExample {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello, " + name);
}
}

We can import packages using the import keyword in three ways:


1. Importing a Single Class
We import only the required class from a package.
import java.util.Scanner; // imports only the Scanner class

2. Importing All Classes from a Package


We use a * wildcard to import all classes from a package.
import java.util.*; // imports all classes in java.util package

3. Using Fully Qualified Name


We don’t use import at all; instead, we directly specify the package name with the class name.
java.util.Scanner sc = new java.util.Scanner(System.in);
Example Program: Importing a Package
import java.util.Scanner; // importing Scanner class from java.util package

class PackageExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // using Scanner class
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello, " + name + "!");
sc.close();
}
}

Explanation:
●​ import java.util.Scanner; tells Java to bring only the Scanner class from the java.util package.
●​ The program uses the Scanner object to read user input.

6. Write a Java program to create an interface Flyable with a method called fly_obj(). Create
three classes Spacecraft, Airplane, and Helicopter that implement the Flyable interface.
Implement the fly_obj() method for each of the three classes.
// Interface
interface Flyable {
void fly_obj(); // abstract method
}

// Spacecraft class
class Spacecraft implements Flyable {
@Override
public void fly_obj() {
System.out.println("Spacecraft is flying into outer space!");
}
}

// Airplane class
class Airplane implements Flyable {
@Override
public void fly_obj() {
System.out.println("Airplane is flying high in the sky!");
}
}

// Helicopter class
class Helicopter implements Flyable {
@Override
public void fly_obj() {
System.out.println("Helicopter is hovering above the ground!");
}
}

// Main class to test


public class Main {
public static void main(String[] args) {
Flyable spacecraft = new Spacecraft();
Flyable airplane = new Airplane();
Flyable helicopter = new Helicopter();

spacecraft.fly_obj();
airplane.fly_obj();
helicopter.fly_obj();
}
}

●​ Flyable is an interface with one method fly_obj().


●​ Spacecraft, Airplane, and Helicopter implement Flyable and override fly_obj() to give their
specific flying behavior.
●​ The main method demonstrates polymorphism by calling the method on different objects via
the same interface reference.

7. Write a Java program to create an abstract class Animal with an abstract method called
sound(). Create subclasses Lion and Tiger that extend the Animal class and implement the
sound() method to make a specific sound for each animal.

// Abstract class
abstract class Animal {
// Abstract method
abstract void sound();
}

// Lion subclass
class Lion extends Animal {
@Override
void sound() {
System.out.println("Lion roars: Roarrr!");
}
}

// Tiger subclass
class Tiger extends Animal {
@Override
void sound() {
System.out.println("Tiger growls: Grrrr!");
}
}

// Main class to test


public class Main {
public static void main(String[] args) {
Animal lion = new Lion();
Animal tiger = new Tiger();

lion.sound(); // Calls Lion's sound method


tiger.sound(); // Calls Tiger's sound method
}
}
●​ Animal is declared as an abstract class with an abstract method sound().
●​ Lion and Tiger extend Animal and override sound() to give specific outputs.
●​ In main, we create Animal references but instantiate them as Lion and Tiger, demonstrating
polymorphism.

8. Write a Java program to create an interface Playable with a method play() that takes no
arguments and returns void. Create three classes Football, Volleyball, and Basketball that
implement the Playable interface and override the play() method to play the respective sports.

// Interface
interface Playable {
void play(); // abstract method
}

// Football class
class Football implements Playable {
@Override
public void play() {
System.out.println("Playing Football: Kicking the ball!");
}
}

// Volleyball class
class Volleyball implements Playable {
@Override
public void play() {
System.out.println("Playing Volleyball: Serving the ball!");
}
}

// Basketball class
class Basketball implements Playable {
@Override
public void play() {
System.out.println("Playing Basketball: Shooting the ball!");
}
}

// Main class to test


public class Main {
public static void main(String[] args) {
Playable football = new Football();
Playable volleyball = new Volleyball();
Playable basketball = new Basketball();

football.play();
volleyball.play();
basketball.play();
}
}

●​ Playable is an interface with a single abstract method play().


●​ Football, Volleyball, and Basketball each implement Playable and provide their own version
of play().
●​ In main, we create Playable references to demonstrate interface-based polymorphism.

You might also like