23cs301 - Oop Ca1 - QB Ans
23cs301 - Oop Ca1 - QB Ans
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).
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");
}
}
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;
}
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();
}
}
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.println("\nOriginal Array:");
displayArray(arr);
// Insertion Sort
for (int i = 1; i < arr.length; i++) {
int key = arr[i];
int j = i - 1;
sc.close();
}
Output:
Enter number of elements: 6
Enter 6 numbers:
529156
Original Array:
529156
ii.) Explain the structure of the Java Program with an example. (6)
5. Statements
The actual logic of the program inside the main method.
5. (i) Explain Java Development Tool kit and Illustrate the working principles of Java Virtual
Machine. (8)
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
// 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
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();
}
}
}
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.
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;
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;
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;
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
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
}
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.");
}
}
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.");
}
}
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.
public int hashCode() Returns hash code value of the Used in hashing-based
object. collections like HashMap.
Example Program
class Student {
String name;
int rollNo;
// 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;
}
Output:
Area of Rectangle: 15.0
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.
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!");
}
}
spacecraft.fly_obj();
airplane.fly_obj();
helicopter.fly_obj();
}
}
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!");
}
}
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!");
}
}
football.play();
volleyball.play();
basketball.play();
}
}