0% found this document useful (0 votes)
19 views15 pages

OOP Answer-Key

The document consists of multiple-choice questions (MCQs) and descriptive questions (DES) related to Java programming concepts, including exception handling, interfaces, method overloading, and object cloning. Each question tests knowledge on specific Java syntax and functionality, with some requiring the implementation of Java code to demonstrate understanding. The document also includes schemes for grading the answers based on correctness and completeness.

Uploaded by

khushpatel1222
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)
19 views15 pages

OOP Answer-Key

The document consists of multiple-choice questions (MCQs) and descriptive questions (DES) related to Java programming concepts, including exception handling, interfaces, method overloading, and object cloning. Each question tests knowledge on specific Java syntax and functionality, with some requiring the implementation of Java code to demonstrate understanding. The document also includes schemes for grading the answers based on correctness and completeness.

Uploaded by

khushpatel1222
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/ 15

Type: MCQ

Q1. Suppose a and b are two integer variables. How do you test whether exactly one of them is zero?
Identify the correct statement. (0.5)

1. ( a == 0 && b != 0 ) &&( b == 0 && a != 0 )


2. **( a == 0 && b != 0 ) || ( b == 0 && a != 0 )
3. ( a == 0 || b != 0 ) || ( b == 0 || a != 0 )
4. ( a == 0 || b != 0 ) && ( b == 0 && a != 0 )
Q2. Select the valid statement. (0.5)
1. **double[] db = new double[5]
2. double[] db = new double()
3. double[] db = new double []
4. double[] db = new double (5)
Q3. What is the minimum number of argument/s that can be passed to “public static void main(String[]
args)”? (0.5)
1. 2
2. 1
3. **0
4. More than 2
Q4. What value is returned by the compareTo() method in case the invoking string happens to be
greater than the compared string? (0.5)

1. **a value that is greater than zero


2. a value that is less than zero
3. Zero
4. None of these
Q5. What will be the output of the following Java code?

public class Demo{


public static void main(String[] args)
{
byte i = 97;

System.out.println((char)i);
}
} (0.5)
1. ** a
2. 1100001
3. A
4. ‘97’

Q6. Which of these access specifiers can be used for an interface? (0.5)
1. **public
2. protected
3. private
4. All of these
Q7. Which of these keywords must be used to monitor for exceptions? (0.5)

1. catch
2. **try
3. finally
4. throw
Q8. What will be the output of the following code?
class exception_handling
{
public static void main(String arg[])
{
try{
System.out.println("Exception" + " " + 1 / 0);
}
catch(ArithmeticException e){
System.out.println("handled");
}
}
}

(0.5)

1. Exception
2. Exception handled
3. **handled
4. No output

Q9. Which of these keywords is not a part of exception handling? (0.5)


1. try
2. finally
3. **thrown
4. Catch
Q10. Which of the following class is used to convert the date from one format to the other (0.5)
1. Date
2. SimpleDate
3. **SimpleDateFormat
4. DateConverter

Type: DES

Q11. Write a Java program to calculate the total salary of 'n' employees by implementing salary and
allowances interfaces. The salary is calculated based on Basic Pay, HRA (12% of basic pay), and DA
(6.5% of Basic Pay). The allowances are calculated based on Travel Allowance (TA), Medical
Allowance (MA), and Food Allowance (FA).
Gross Salary (GS)=Basic Pay + HRA+DA.
Allowances= TA + MA + FA
Assuming, IT = 10% of GS, PF = 12% of Basic pay, Professional Tax=200.
Net Salary (NS) = GS + Allowances - (IT+ PF +PT)

Note: The program should ask the user for the number of employees and prompts for inputs like Basic
Pay, TA, MA, and FA for each employee. Calculate and print the net salary for each employee. (4)

Scheme:
salary interface with a method → 0.5 mark
Allowance interface with a method → 0.5 mark
Implementation of above interfaces by a class → 2 marks
Main method with Array of objects to process ‘n’ students → 1 mark
import java.util.Scanner;

// Interface to calculate salary components


interface Salary
{
void calculateSalary(); // Method to calculate salary
}

// Interface to calculate allowance components


interface Allowances
{
void calculateAllowance(); // Method to calculate allowances
}

// Employee class implementing Salary and Allowances interfaces


class Employee implements Salary, Allowances
{
private double basicPay;
private double HRA;
private double DA;
private double grossSalary;
private double TA; // Travel Allowance
private double MA; // Medical Allowance
private double FA; // Food Allowance
private double totalAllowances;
private double netSalary;

// Constructor to initialize fields


public Employee(double basicPay, double TA, double MA, double FA)
{
this.basicPay = basicPay;
this.TA = TA;
this.MA = MA;
this.FA = FA;
}

// Method to calculate Gross Salary (GS)


public void calculateSalary()
{
HRA = 0.12 * basicPay;
DA = 0.065 * basicPay;
grossSalary = basicPay + HRA + DA;
}

// Method to calculate Allowances (TA + MA + FA)


public void calculateAllowance()
{
totalAllowances = TA + MA + FA;
}

// Method to calculate Net Salary (NS)


public void calculateNetSalary()
{
double IT = 0.10 * grossSalary; // Income Tax
double PF = 0.12 * basicPay; // Provident Fund
double PT = 200; // Professional Tax

netSalary = grossSalary + totalAllowances - (IT + PF + PT);


}

// Method to display employee salary details


public void displaySalaryDetails(int empId)
{
System.out.println("Employee ID: " + empId);
System.out.println("Gross Salary (GS):" +grossSalary);
System.out.println("Total Allowances: " +totalAllowances);
System.out.println("Net Salary (NS): " +netSalary);
}
}

class EmployeeDemo
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);

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


int n = scanner.nextInt();
// Array of Employee objects
Employee[] employees = new Employee[n];

// Loop to input details for each employee


for (int i = 0; i < n; i++)
{
System.out.println("Enter details for Employee " + (i + 1) + ":");
System.out.print("Basic Pay: ");
double basicPay = scanner.nextDouble();
System.out.print("Travel Allowance (TA): ");
double TA = scanner.nextDouble();
System.out.print("Medical Allowance (MA): ");
double MA = scanner.nextDouble();
System.out.print("Food Allowance (FA): ");
double FA = scanner.nextDouble();

// Create a new Employee object and store it in the array


employees[i] = new Employee(basicPay, TA, MA, FA);

// Calculate salary and allowances for the employee


employees[i].calculateSalary();
employees[i].calculateAllowance();
employees[i].calculateNetSalary();
}
// Display the salary details for each employee
for (int i = 0; i < n; i++)
{
employees[i].displaySalaryDetails(i + 1);
}
}
}
Q12. Create a class that contains a 1D array of double as an instance variable. Define a static method
that swaps the lowest value in the array of one object with the lowest value in the array of another
object, without sorting the arrays. The static method should take two objects of the class (say, x and
y) as arguments. Write a complete Java program that includes the class definition, the static method
for swapping the lowest values, and a demonstration in the main method. (3)
Scheme:
Static method with correct syntax → 1 mark
Correct logic for swapping the lowest value in the array of one object with the lowest value in the
array of another object → 1 mark
Main () with proper method call statement → 1 mark
class ArraySwap
{
private double[] array;

public ArraySwap(double[] array)


{
this.array = array;
}

public static void swapLowestValues(ArraySwap x, ArraySwap y)


{
int xIndex = findLowestIndex(x.array);
int yIndex = findLowestIndex(y.array);

// Swap the lowest values


double temp = x.array[xIndex];
x.array[xIndex] = y.array[yIndex];
y.array[yIndex] = temp;
}

private static int findLowestIndex(double[] arr)


{
int lowestIndex = 0;
double lowestValue = arr[0];

for (int i = 1; i < arr.length; i++)


{
if (arr[i] < lowestValue)
{
lowestIndex = i;
lowestValue = arr[i];
}
}

return lowestIndex;
}

public void printArray()


{
for( double ele : array )
System.out.print( ele +"\t" );
}
}
class ArrayswapDemo
{
public static void main(String[] args)
{
double[] array1 = {3.5, 1.2, -7.8, 4.0};
double[] array2 = {9.1, -2.3, 5.6, 8.7};

ArraySwap x = new ArraySwap(array1);


ArraySwap y = new ArraySwap(array2);

System.out.println("Before swapping:");
x.printArray();
y.printArray();

ArraySwap.swapLowestValues(x, y);

System.out.println("\nAfter swapping:");
x.printArray();
y.printArray();
}
}

Q13. Create a class namely "CarInfo" that stores information about a car, such as: its unique identifier
(integer), model name (string), manufacturer (string), year of manufacture (integer), and price (float).
Implement the Cloneable interface to enable the creation of a copy of the CarInfo object. Create
another class with a main method to demonstrate object cloning . (3)

Scheme:
CarInfo class definition with implementation of Cloneable interface: 1 mark
overridden clone () with correct logic in the CarInfo class: 1 mark
Main method with Object cloning statement: 1 mark.

class CarInfo implements Cloneable


{
private int identifier;
private String modelName;
private String manufacturer;
private int yearOfManufacture;
private float price;

public CarInfo(int identifier, String modelName, String manufacturer, int yearOfManufacture, float
price)
{
this.identifier = identifier;
this.modelName = modelName;
this.manufacturer = manufacturer;
this.yearOfManufacture = yearOfManufacture;
this.price = price;
}

public CarInfo clone() throws CloneNotSupportedException


{
return (CarInfo) super.clone();
}

public void setModelName( String name )


{
modelName = name;
}

public String toString()


{
return "CarInfo{" +
"identifier=" + identifier +
", modelName='" + modelName + '\'' +
", manufacturer='" + manufacturer + '\'' +
", yearOfManufacture=" + yearOfManufacture +
", price=" + price +
'}';
}
}

class ObjectCloneDemo
{
public static void main(String[] args)
{
CarInfo car1 = new CarInfo(1, "Model A", "Company X", 2023, 25000.0f);
System.out.println("Original car: " + car1);

try
{
CarInfo car2 = car1.clone();
System.out.println("Cloned car: " + car2);

car2.setModelName("Model B");
System.out.println("Modified cloned car: " + car2);
System.out.println("Original car: " + car1);
}
catch (CloneNotSupportedException e)
{
System.out.println("Object Cloning failed !!!");
}
}
}

Q14. Consider a parent class as Animal with a method as makeSound(). Create two child classes as
Dog and Cat and demonstrate dynamic method dispatch in the main class for invoking the
makeSound() method of respective classes through parents class reference. (3)
Scheme:

class Animal {
void makeSound() {
System.out.println("Some sound");
}
}

class Dog extends Animal { //---0.5


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

class Cat extends Animal { //---0.5


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

public class MainClass {


public static void main(String[] args) {
Animal myDog = new Dog(); //----0.5M
Animal myCat = new Cat(); //----0.5M

myDog.makeSound(); // Expected Output: Woof ---- 0.5M


myCat.makeSound(); // Expected Output: Meow ----- 0.5M
}
}

Q15. Illustrate three String class methods with appropriate examples and provide syntax for the same.
. (3)
Scheme:
Three methods, 1 M each with example and syntax
Q16. Write a Java program to demonstrate how to create and use a user-defined exception. The
program should throw a custom exception called InvalidAgeException when a user enters an age
below 18. Use the throw keyword to throw this exception manually. Explain how the custom exception
is handled in the program. (3)
Scheme:
// User-defined exception class ----- 1M
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}

public class CustomExceptionExample {


// Method to validate age and throw custom exception
public static void validateAge(int age) throws InvalidAgeException { ---1M
if (age < 18) {
throw new InvalidAgeException("Age must be 18 or above."); ----1M
} else {
System.out.println("Valid age.");
}
}

public static void main(String[] args) {


try {
validateAge(16); // This will throw the InvalidAgeException
} catch (InvalidAgeException e) {
System.out.println("Caught Exception: " + e.getMessage());
} finally { //optional
System.out.println("Validation process completed.");
}
}
}

Q17. Differentiate between checked and unchecked exceptions with examples. (2)

Scheme: 1 mark each

Compile-time exceptions (checked exceptions) are checked at compile time. The compiler ensures
these exceptions are either handled using try-catch blocks or declared using the throws keyword.
Examples: IOException, SQLException.

Runtime exceptions (unchecked exceptions) occur during program execution and are not checked
by the compiler. Examples: ArithmeticException, NullPointerException.

Q18. Write a Java program that demonstrates method overloading with variable-length arguments
(varargs) to calculate the product of integers. Explain the impact of overloading with variable-length
arguments on code flexibility. (2)
Scheme: 1.5 M for program with overloading,
0.5 for explanation

Code:
public class OverloadVarArgsExample {
// Method with fixed arguments
public static int multiply(int a, int b) {
return a * b;
}

// Method with variable-length arguments


public static int multiply(int... numbers) {
int result = 1;
for (int num : numbers) {
result *= num;
}
return result;
}

public static void main(String[] args) {


System.out.println("Product (fixed args): " + multiply(3, 4));
System.out.println("Product (varargs): " + multiply(2, 3, 4, 5));
}
}

Q18. For the given output below, fill in the code snippet.

Output:

Outer data: 10

Inner data: 20

//Program:

class Outer {
private int outerData = 10;

class Inner {

private int innerData = 20;

public void displayData() {

System.out.println("Outer data: " + __________); // Fill in the blank

System.out.println("Inner data: " + ___________); // Fill in the blank

public void createInnerInstance() {

Inner inner = ________________ // Fill in the blank

inner.displayData();

public static void main(String[] args) {

Outer outer = _________________ // Fill in the blank

outer.createInnerInstance();

} . (2)

Scheme:
class Outer {
private int outerData = 10;

class Inner {
private int innerData = 20;

public void displayData() {


System.out.println("Outer data: " + outerData); // Fill in the blank ---- 0.5
System.out.println("Inner data: " + innerData); // Fill in the blank ---- 0.5
}
}
public void createInnerInstance() {
Inner inner = new Inner(); // Fill in the blank ---- 0.5
inner.displayData();
}

public static void main(String[] args) {


Outer outer = new Outer(); // Fill in the blank ---- 0.5
outer.createInnerInstance();
}
}

You might also like