Model Questions Solutions OOP Java IA 2
Model Questions Solutions OOP Java IA 2
Output:
Sum of integers: 8
Sum of doubles: 6.0
2. Illustrate the difference between the access modifiers – Private, Public and Protected through a
suitable example and code snippet.
Solution: Access Modifiers
- Private: Only accessible within the same class.
- Protected: Accessible within the same package and subclasses.
- Public: Accessible from any class.
- Code Snippet:
class AccessModifiersExample {
private int privateVariable; // Accessible only within this class
protected int protectedVariable; // Accessible within the package and subclasses
public int publicVariable; // Accessible from everywhere
class AccessModifiersExample {
private int privateVariable; // Accessible only within this class
protected int protectedVariable; // Accessible directly within the same package
public int publicVariable; // Accessible from everywhere
3. Illustrate Recursion for the following with int n1 as input: a) Factorial of n1 b) Sum of all Numbers
upto n1.
Solution:
import java.util.Scanner;
if (n1 < 0) {
System.out.println("Please enter a positive integer.");
} else {
// Calculate and display results
int factorialResult = factorial(n1);
int sumResult = sumUpTo(n1);
4. Create a class called StudentResume. Within this, create 2 nested classes CollegeAddress,
HomeAddress. Write constructor methods to print address containing location, city, pincode, state. In
public class TestStudentResume, create objects of the outer class and the two inner classes. Depending
on user input, print the resume and the respective address.
Solution:
import java.util.Scanner;
class StudentResume {
System.out.println("\nDo you want to print College or Home Address? (Enter 'college' or 'home')");
String addressChoice = scanner.nextLine().toLowerCase();
if (addressChoice.equals("college")) {
collegeAddress.printCollegeAddress();
} else if (addressChoice.equals("home")) {
homeAddress.printHomeAddress();
} else {
System.out.println("Invalid choice!");
}
scanner.close();
}
}
Example:
class Counter {
static int count = 0; // Static variable shared among all instances
Counter() {
count++; // Increment count for each object creation
}
void displayCount() {
System.out.println("Count: " + count);
}
}
c1.displayCount(); // Count: 3
c2.displayCount(); // Count: 3
c3.displayCount(); // Count: 3
}
}
Example:
class MathOperations {
// Static method for addition
static int add(int a, int b) {
return a + b;
}
}
Example:
class Config {
static String appName;
static int version;
Output:
Static block executed!
App Name: MyApp
Version: 1
Example:
class OuterClass {
static class NestedClass {
void displayMessage() {
System.out.println("Hello from Static Nested Class!");
}
}
}
6. Illustrate Method Overloading with suitable example to demonstrate No parameter, Passing of two
parameters, Passing an object.
Solution:
class Calculator {
Output:
No parameters provided for addition.
Sum of 10 and 20 is: 30
Sum using object (array): 75
7. Create class InternalMarks, created two NestedClasses IA and Lab. Within IA class, create method
showmarks(int n1). If student has got marks 15, 20, 18 in three IAs, only best two should be considered.
Write a working program. (you may get this question in IA like this, but should be interpreted as the
corrected one)
Solution:
class InternalMarks {
// Nested Class IA
class IA {
void showMarks(int n1, int n2, int n3) {
// Find the lowest mark among the three using Math.min
int lowest = Math.min(n1, Math.min(n2, n3));
// Calculate the total of the best two marks by subtracting the lowest mark
int totalBestTwo = (n1 + n2 + n3) - lowest;
Output:
Marks in three IAs: 15, 20, 18
Best two marks total: 38
Lab marks functionality can be added here.
8. Create a class Box having attributes length, width and height. A small box has dimensions (3,4,5). A
large box has dimensions (10,20,30). Every box has 6 faces. Declare this as a static attribute. Write
methods to compute the volume of SmallBox b1 and LargeBox b2.
Solution:
class Box {
// Attributes for dimensions of the box
private int length, width, height;
Output:
SmallBox Dimensions: Length = 3, Width = 4, Height = 5
Number of Faces: 6
Volume: 60
Key Points:
// Superclass
class Animal {
// Method to be overridden
// Subclass
@Override
System.out.println("Dogs bark");
Output:
Dogs bark
10. When is “final” used for variables? When is “final” used for methods? Why? Write a suitable code
snippet.
Solution:
1. Final Variables:
o To define constants like PI, MAX_VALUE, etc.
o To prevent accidental modification of critical data.
2. Final Methods:
o To ensure the base class method's functionality is preserved and not altered by subclasses.
Code snippet:
class ParentClass {
final double PI = 3.14159; // Final variable (constant)
// Intermediate class
class CSE extends SMVITM {
protected String departmentName = "CSE"; // Department name
// Derived class
class Batch4MW23CS extends CSE {
private String[] usns = new String[54]; // Array to hold USNs for 50 students + 4 unallocated
// Main class
public class MultiLevelInheritanceDemo {
public static void main(String[] args) {
// Create an object of the most derived class
Batch4MW23CS batch = new Batch4MW23CS();
Output:
College: SMVITM
Total Students with USNs: 50
Department: CSE
USNs of students:
Student 1: 4MW23CS001
Student 2: 4MW23CS002
...
Student 50: 4MW23CS050
Student 51: No USN Allocated
Student 52: No USN Allocated
Student 53: No USN Allocated
Student 54: No USN Allocated
12. Illustrate the use of “super” keyword using suitable example. Dog is a child class of Animal.
getColour() in Animal class gives black, getColour() in Dog class gives white. Write Java code using
“super”.
Solution:
// Parent class
class Animal {
// Method in the parent class
public String getColour() {
return "Black";
}
}
// Child class
class Dog extends Animal {
// Overriding the method in the child class
@Override
public String getColour() {
return "White";
}
// Main class
public class SuperKeywordDemo {
public static void main(String[] args) {
// Create an object of the Dog class
Dog dog = new Dog();
Output:
Dog's Colour: White
Animal's Colour: Black
Solution:
Key Features:
1. Inheritance:
o Every Java class implicitly extends Object.
o Example:
class MyClass { } // Implicitly extends Object
2. Core Methods:
o toString(): Returns a string representation of the object.
o equals(Object obj): Compares objects for equality.
o hashCode(): Provides a hash code for the object.
o getClass(): Returns the runtime class of the object.
o wait(), notify(), notifyAll(): Used in thread synchronization.
Example:
toString() and equals():
class MyClass {
int value;
MyClass(int value) {
this.value = value;
}
@Override
public String toString() {
return "Value: " + value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
MyClass other = (MyClass) obj;
return value == other.value;
}
}
14. A car showroom needs a billing system for different car models. Write a program illustrating a muti-
level inheritance with the following classes. Vehicle, 4Wheeler, MarutiSuzuki, Alto, Celerio, Swift.
Only the Swift model has method automaticDrive(). Other models have method manualDrive() only.
Create a simple billing system for the showroom.
Solution:
import java.util.Scanner;
// Base class
class Vehicle {
public void displayType() {
System.out.println("This is a vehicle.");
}
}
double price = 0;
switch (choice) {
case 1:
Alto alto = new Alto();
alto.displayType();
alto.displayCategory();
alto.displayBrand();
alto.manualDrive();
price = alto.getPrice();
break;
case 2:
Celerio celerio = new Celerio();
celerio.displayType();
celerio.displayCategory();
celerio.displayBrand();
celerio.manualDrive();
price = celerio.getPrice();
break;
case 3:
Swift swift = new Swift();
swift.displayType();
swift.displayCategory();
swift.displayBrand();
swift.automaticDrive();
price = swift.getPrice();
break;
default:
System.out.println("Invalid choice! Please select a valid model.");
return;
}
Output:
Welcome to the Car Showroom!
Available Models: 1. Alto 2. Celerio 3. Swift
Enter the model number you want to purchase: 2
This is a vehicle.
This is a 4-Wheeler.
This is a Maruti Suzuki car.
Celerio supports manual driving.
Enter the quantity of cars you want to purchase: 2
15. Write a Java program having class SmartPhone inherited from parent class ElectronicDevice and
from interfaces “GPS”, “Radio” and “Bluetooth”. Declare a method in each interface and implement
them in the child class. In public class TestSmartPhone, print the features of 2 different models.
Solution:
// Parent class
class ElectronicDevice {
private String brand;
public ElectronicDevice(String brand) {
this.brand = brand;
}
// GPS Interface
interface GPS {
void navigate();
}
// Radio Interface
interface Radio {
void playRadio();
}
// Bluetooth Interface
interface Bluetooth {
void connectBluetooth();
}
@Override
public void navigate() {
System.out.println(model + " has GPS navigation feature.");
}
@Override
public void playRadio() {
System.out.println(model + " can play FM radio.");
}
@Override
public void connectBluetooth() {
System.out.println(model + " supports Bluetooth connectivity.");
}
// Main class
public class TestSmartPhone {
public static void main(String[] args) {
// Creating two different smartphone models
SmartPhone phone1 = new SmartPhone("BrandA", "ModelX");
SmartPhone phone2 = new SmartPhone("BrandB", "ModelY");
Output:
Features of BrandA ModelX:
BrandA device is powered on.
ModelX has GPS navigation feature.
ModelX can play FM radio.
ModelX supports Bluetooth connectivity.
BrandA device is powered off.
16. Federal Express is a courier service having different rates for shipping -small boxes, big boxes, fragile
boxes. Federal Express also wants to add GST to the pricing through an interface “Taxable” Write a Java
code to illustrate using inheritance of class and interface.
Solution:
// Interface for Taxable
interface Taxable {
double GST_RATE = 0.18; // 18% GST
@Override
public double calculateGST(double basePrice) {
return basePrice * GST_RATE;
}
}
@Override
public double calculateGST(double basePrice) {
return basePrice * GST_RATE;
}
}
// Child class: FragileBox
class FragileBox extends CourierService implements Taxable {
public FragileBox(double basePrice) {
super("Fragile Box", basePrice);
}
@Override
public double calculateGST(double basePrice) {
return basePrice * GST_RATE;
}
}
// Main class
public class FederalExpress {
public static void main(String[] args) {
// Create instances of different box types
SmallBox smallBox = new SmallBox(200);
BigBox bigBox = new BigBox(500);
FragileBox fragileBox = new FragileBox(1000);
Big Box:
Box Type: Big Box
Base Price: Rs.500.0
GST: Rs.90.0
Total Price: Rs.590.0
Fragile Box:
Box Type: Fragile Box
Base Price: Rs.1000.0
GST: Rs.180.0
Total Price: Rs.1180.0