Marking scheme · model solutions
CHANDIGARH UNIVERSITY
Bachelor of Engineering — Computer Science & Engineering / Information Technology
MID-SEMESTER TEST I · MODEL SOLUTIONS
Project Based Learning in Java — 24CSH-301 / 24ITH-301
Section A — 2 Mark Questions
5 × 2 = 10 MarksExplain the role of the static keyword in Java and provide an example demonstrating its usage.
A static member belongs to the class rather than to each object. One copy of a static field is shared by all objects, and a static method is normally called through the class name without creating an object. A static method cannot directly access instance members because it has no current object.
class Student {
static int count = 0; // one class-level copy
Student() { count++; }
public static void main(String[] args) {
new Student();
new Student();
System.out.println(Student.count); // 2
}
}
- Correct explanation of the role of
staticin Java — 1 mark - Appropriate example or syntax demonstrating its use — 1 mark
Discuss when it is appropriate to use the protected access modifier in Java classes.
A protected member is accessible inside its declaring class, by every class in the same package, and by subclasses in other packages through inheritance. Across packages, an instance member must be accessed through the subclass's own type or a subtype, not through an arbitrary superclass object.
Use protected when a parent class must expose selected implementation details to child classes without making those details public. Keeping fields private and exposing protected methods often gives tighter control.
class Animal {
protected String name = "Animal";
protected void describe() {
System.out.println(name);
}
}
class Dog extends Animal {
void show() {
name = "Dog";
describe();
}
}
- Correct explanation of the scope and purpose of
protected— 1 mark - Appropriate use in inheritance or a suitable example — 1 mark
Explain how Java achieves platform independence.
The javac compiler translates a .java source file into platform-neutral bytecode stored in a .class file. Bytecode targets the instruction set of the Java Virtual Machine, not the native instruction set of one processor or operating system.
Each operating system supplies its own platform-specific JVM. The JVM interprets or JIT-compiles the same bytecode into local machine instructions, so the same .class file can run unchanged on Windows, Linux, or macOS when compatible libraries are available.
Java source (.java)
| javac
v
Bytecode (.class) -- platform-neutral
|-- Windows JVM --> Windows machine code
|-- Linux JVM --> Linux machine code
`-- macOS JVM --> macOS machine code
Write Once, Run Anywhere
- Source compilation into bytecode and the role of the JVM — 1 mark
- Explanation that the same bytecode runs on different platforms, or a suitable diagram — 1 mark
Discuss the role of interfaces in achieving multiple inheritance in Java.
An interface defines a type and a behavioural contract. A class that implements it promises to provide the required methods. Interfaces support abstraction without giving a class multiple copies of parent-class instance state.
interface Printable { void print(); }
interface Showable { void show(); }
class Report implements Printable, Showable {
public void print() { System.out.println("Printing"); }
public void show() { System.out.println("Showing"); }
}
Report inherits both interface types, so Java supports multiple inheritance of type through interfaces while allowing a class to extend only one class. If inherited default methods conflict, the class must override the method and resolve the conflict explicitly.
- Correct explanation of an interface and its role — 1 mark
- Explanation or suitable syntax showing a class implementing multiple interfaces — 1 mark
Define throw and throws keywords.
throw is a statement inside a method or block that immediately throws one Throwable object and transfers control to the nearest matching handler.
throw new IllegalArgumentException("Amount must be positive");
throws is a clause in a method declaration that lists exception types the method may propagate to its caller. It does not throw or handle an exception by itself. It is required when an unhandled checked exception can escape and optional for unchecked exceptions.
static String load(Path path) throws IOException {
return Files.readString(path);
}
- Correct definition or explanation of
throw— 1 mark - Correct definition or explanation of
throws— 1 mark
Section B — 5 Mark Questions
2 × 5 = 10 MarksImplement an abstract class Product with an abstract method calculateDiscount(). Create subclasses Electronics, Clothing, and Furniture. Override the method to calculate discounts according to product category. Display product information and final price after discount.
Product stores the common data and display logic. The abstract method returns the discount amount, and dynamic dispatch selects the correct subclass implementation at run time.
abstract class Product {
private final String name;
private final double price;
protected Product(String name, double price) {
this.name = name;
this.price = price;
}
protected double getPrice() { return price; }
public abstract double calculateDiscount();
public void display() {
double discount = calculateDiscount();
double finalPrice = price - discount;
System.out.printf(
"%s | Price: %.2f | Discount: %.2f | Final price: %.2f%n",
name, price, discount, finalPrice);
}
}
class Electronics extends Product {
Electronics(String name, double price) { super(name, price); }
@Override
public double calculateDiscount() { return getPrice() * 0.10; }
}
class Clothing extends Product {
Clothing(String name, double price) { super(name, price); }
@Override
public double calculateDiscount() { return getPrice() * 0.20; }
}
class Furniture extends Product {
Furniture(String name, double price) { super(name, price); }
@Override
public double calculateDiscount() { return getPrice() * 0.15; }
}
public class ProductDemo {
public static void main(String[] args) {
Product[] products = {
new Electronics("Laptop", 50000),
new Clothing("Jacket", 3000),
new Furniture("Chair", 10000)
};
for (Product product : products) {
product.display();
}
}
}
Expected output
Laptop | Price: 50000.00 | Discount: 5000.00 | Final price: 45000.00
Jacket | Price: 3000.00 | Discount: 600.00 | Final price: 2400.00
Chair | Price: 10000.00 | Discount: 1500.00 | Final price: 8500.00
- Correct abstract
Productclass and abstractcalculateDiscount()method — 1 mark - Correct
Electronics,Clothing, andFurnituresubclasses — 1½ marks - Correct overrides with category-specific discount calculations — 1½ marks
- Correct display of product information and final price after discount — 1 mark
Classify the exception class hierarchy in Java and provide a program to illustrate the handling of unchecked exceptions, discussing the significance and potential scenarios where unchecked exceptions may arise.
Throwable is the root of everything that can be thrown or caught. Its two main branches are Error and Exception. RuntimeException is a subclass of Exception. RuntimeException and its subclasses are unchecked, and the Error family is also unchecked. The remaining Throwable classes are checked.
Object
`-- Throwable
|-- Error (unchecked)
| |-- OutOfMemoryError
| `-- StackOverflowError
`-- Exception
|-- RuntimeException (unchecked)
| |-- ArithmeticException
| |-- NullPointerException
| `-- NumberFormatException
`-- Other Exception subclasses (checked)
|-- IOException
`-- SQLException
Checked exceptions are subject to the compiler's catch-or-declare rule. Unchecked exceptions do not have to be caught or listed in a throws clause. Runtime exceptions commonly signal a violated method contract, invalid state, failed conversion, or programming defect.
public class UncheckedExceptionDemo {
public static void main(String[] args) {
int dividend = 10;
int divisor = 0;
try {
int quotient = dividend / divisor;
System.out.println("Quotient: " + quotient);
} catch (ArithmeticException ex) {
System.out.println("Cannot divide by zero.");
}
System.out.println("Program continues normally.");
}
}
Expected output
Cannot divide by zero.
Program continues normally.
Unchecked exceptions often reveal defects or violated preconditions. They should usually be prevented with sound logic and input validation, then caught only where the program can respond meaningfully. If an unchecked exception is not handled, it propagates up the call stack and can terminate the current thread.
| Typical scenario | Unchecked exception |
|---|---|
| Integer division by zero | ArithmeticException |
| Dereferencing a null reference | NullPointerException |
| Using an invalid array index | ArrayIndexOutOfBoundsException |
| Converting non-numeric text to a number | NumberFormatException |
| Passing an invalid method argument | IllegalArgumentException |
- Correct classification of the exception hierarchy and the role of
RuntimeException— 1½ marks - Clear, correctly structured program that handles an unchecked exception — 2½ marks
- Significance and suitable scenarios where unchecked exceptions may arise — 1 mark