BJECT ORIENTED PROGRAMMING — MODEL EXAMINATION ANSWER
Group D | Anna University — B.E./[Link] CSE | Java Programming
Register No. : ____________________ Name : ____________________
Subject : Java Programming (Object Oriented Programming)
Exam : Model Exam — Group D
SECTION A — Short Answer Questions (3 marks each)
1. Differentiate between = and == in Java.
Basis = (Assignment) == (Equality)
Meaning Assignment operator. Stores the value Equality (relational) operator.
on the right‑hand side into the variable Compares two values or references and
on the left. returns a boolean result.
Purpose Used to give / change the value of a Used inside conditions, loops, decisions
variable. (if, while, for) to test equality.
Returns No boolean result; it performs an Returns true or false.
action.
Object use int a = 5; assigns 5 to a. For objects, == compares references
(addresses), not content (use .equals()
for content).
Example int x = 10; if (x == 10) { ... }
int a = 5; // '=' stores 5 into a
if (a == 5) { // '==' compares a with 5
[Link]("Equal");
}
[3/3 marks]
2. Differentiate between the break and continue statements.
Basis break continue
Action Terminates the loop (or switch) Skips only the current iteration and
immediately and exits it completely. moves to the next iteration of the loop.
Control flow Control jumps to the statement right Control jumps back to the loop's
after the loop. update/condition check.
Usable in Loops (for, while, do-while) and switch Only loops (for, while, do-while).
statements.
Effect on All remaining iterations are cancelled. Remaining iterations still execute,
remaining current one is skipped.
iterations
Page 1
Java Programming — Answer Script Group D
for (int i = 1; i <= 5; i++) {
if (i == 3) break; // loop stops entirely at i = 3
[Link](i);
}
// Output: 1 2
for (int i = 1; i <= 5; i++) {
if (i == 3) continue; // only i = 3 is skipped
[Link](i);
}
// Output: 1 2 4 5
[3/3 marks]
3. What is a method signature? Give an example.
A method signature is the combination of the method name together with the number,
type, and order of its parameters. It is what the Java compiler uses to uniquely identify
a method — it does not include the return type or the access modifier.
Signature = methodName(parameter-type-list)
public int add(int a, int b) { ... }
// Method signature: add(int, int)
public double add(double a, double b) { ... }
// Different signature: add(double, double)
// -> This is what enables method OVERLOADING.
Two methods in the same class cannot have the same signature, even if their return types
differ.
[3/3 marks]
4. Differentiate between a default constructor and a parameterized
constructor.
Basis Default Constructor Parameterized Constructor
Definition A constructor with no arguments; A constructor that accepts one or more
either written by the programmer or parameters to initialise an object with
auto‑supplied by Java when no specific values.
constructor is defined.
Initialisation Initialises fields with default values (0, Initialises fields with values passed by
null, false) or fixed values. the caller at the time of object creation.
Provided auto Yes, if the class defines no constructor Never provided automatically; must
matically? at all. always be written explicitly.
Example call Student s = new Student(); Student s = new Student("Bindhu",
21);
Page 2
Java Programming — Answer Script Group D
class Student {
String name; int age;
Student() { // default constructor
name = "Unknown"; age = 0;
}
Student(String n, int a) { // parameterized constructor
name = n; age = a;
}
}
[3/3 marks]
5. State the difference between method overloading and method
overriding.
Basis Overloading Overriding
Definition Same method name with different Subclass redefines a method that
parameter lists within the SAME class. already exists (same signature) in its
superclass.
Inheritance Not required. Required — needs a parent‑child (IS‑A)
needed? relationship.
Binding Resolved at compile time (static / early Resolved at run time (dynamic / late
binding). binding), via polymorphism.
Parameters / Must differ in number, type, or order. Must be exactly the same as the parent
signature method.
Return type Can be different. Must be the same or a covariant type.
[3/3 marks]
Page 3
Java Programming — Answer Script Group D
SECTION B — Long Answer / Program Questions (15 marks
each)
1. [Program] E-commerce checkout — ternary & logical operators
(a) Program using ternary and logical operators to compute final payable
amount.
import [Link];
public class CheckoutDiscount {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Enter cart total: ");
double cartTotal = [Link]();
[Link]("Is customer a premium member? (true/false): ");
boolean isPremium = [Link]();
double threshold = 2000.0; // discount eligibility threshold
// Ternary + logical operator: discount applies ONLY IF
// cartTotal exceeds threshold AND customer is premium
double discount = (cartTotal > threshold && isPremium) ? cartTotal * 0.10 : 0.0;
double finalAmount = cartTotal - discount;
[Link]("Discount applied : " + discount);
[Link]("Final Payable Amount : " + finalAmount);
}
}
Enter cart total: 2500
Is customer a premium member? (true/false): true
Discount applied : 250.0
Final Payable Amount : 2250.0
Explanation: The logical AND (&&) combines the two conditions (cart above threshold,
premium member) into a single boolean. The ternary operator (condition ? value1
: value2) then chooses the 10% discount only when both conditions are true;
otherwise the discount stays 0.
[9/9 marks]
(b) Extend the program to apply an additional festive discount using a
nested ternary operator.
Page 4
Java Programming — Answer Script Group D
// ... continuing from part (a) ...
[Link]("Enter festive season code (1=Diwali,2=NewYear,0=None): ");
int season = [Link]();
double afterDiscount = cartTotal - discount;
// Nested ternary: extra festive discount stacked on top
double festiveDiscount = (season == 1) ? afterDiscount * 0.05
: (season == 2) ? afterDiscount * 0.08
: 0.0;
double finalPayable = afterDiscount - festiveDiscount;
[Link]("Festive Discount : " + festiveDiscount);
[Link]("Final Amount to Pay: " + finalPayable);
Enter festive season code (1=Diwali,2=NewYear,0=None): 1
Festive Discount : 112.5
Final Amount to Pay: 2137.5
Explanation: The nested ternary checks multiple conditions in sequence (season==1,
else season==2, else none), acting like a compact chained if-else-if, and stacks the
festive discount on top of the membership discount from part (a).
[6/6 marks]
2. [Program] Supermarket inventory scan — labelled nested loops
(a) Program using labelled nested loops with break (out-of-stock) and
continue (expired).
Page 5
Java Programming — Answer Script Group D
public class InventoryScan {
public static void main(String[] args) {
String[][] shelf = {
{"Rice", "Sugar", "OUT_OF_STOCK", "Salt"}, // Aisle 1
{"Soap", "EXPIRED", "Shampoo", "Oil"}, // Aisle 2
{"Milk", "Bread", "Butter", "OUT_OF_STOCK"} // Aisle 3
};
aisleLoop: // label on OUTER loop
for (int aisle = 0; aisle < [Link]; aisle++) {
[Link]("Scanning Aisle " + (aisle + 1));
shelfLoop: // label on INNER loop
for (int shelfNo = 0; shelfNo < shelf[aisle].length; shelfNo++) {
String item = shelf[aisle][shelfNo];
if ([Link]("EXPIRED")) {
continue shelfLoop; // labelled continue: skip only this item
}
if ([Link]("OUT_OF_STOCK")) {
[Link](" Out of stock found -> stop scanning this aisle");
break shelfLoop; // labelled break: stop shelves for THIS aisle only
}
[Link](" Shelf " + (shelfNo + 1) + ": " + item + " - OK");
}
}
}
}
Scanning Aisle 1
Shelf 1: Rice - OK
Shelf 2: Sugar - OK
Out of stock found -> stop scanning this aisle
Scanning Aisle 2
Shelf 1: Soap - OK
Shelf 3: Shampoo - OK
Shelf 4: Oil - OK
Scanning Aisle 3
Shelf 1: Milk - OK
Shelf 2: Bread - OK
Shelf 3: Butter - OK
Out of stock found -> stop scanning this aisle
Note: Both loops are labelled: aisleLoop on the outer loop and shelfLoop on the
inner loop. continue shelfLoop; skips only the current EXPIRED item and resumes
scanning the same aisle. break shelfLoop; is used the moment an OUT_OF_STOCK
item is found — it stops scanning further shelves in that aisle only; the outer
aisleLoop then automatically moves on to the next aisle.
[9/9 marks]
(b) Explain, with a traced example, how the labelled break used here
differs from an unlabelled break in this same nested-loop scenario.
break shelfLoop; in part (a) is a labelled break, but shelfLoop is already the nearest
enclosing loop to that statement. So in this exact program it behaves identically to a
plain, unlabelled break; — both stop only the shelf-scanning loop for the current aisle,
and the outer aisleLoop then proceeds to the next aisle as normal.
Page 6
Java Programming — Answer Script Group D
The real difference between a labelled and an unlabelled break only appears when we
need to break an outer loop from inside an inner one — something a plain break; can
never do, since an unlabelled break always exits just the loop directly surrounding it. A
labelled break can name any enclosing loop, even one several levels up.
Traced comparison (out-of-stock hits Aisle 1, shelf 3):
Stage Unlabelled / break shelfLoop (used Labelled break aisleLoop
in part a) (hypothetical)
What runs break; or break shelfLoop; (both exit only break aisleLoop; (hypothetical — exits the
the shelf loop) OUTER loop too)
Aisle 1 Rice-OK, Sugar-OK, then out-of-stock Rice-OK, Sugar-OK, then out-of-stock
message; shelf loop for Aisle 1 ends message; shelf loop ends
After Aisle aisleLoop continues normally to Aisle 2 aisleLoop itself is terminated immediately
1
Aisle 2 & 3 Both are still scanned (as shown in part Never scanned at all — program's
a's output) scanning ends right there
Conclusion: In this problem, since the requirement is only to stop scanning the current
aisle (not the whole store), a labelled break to the inner loop and an unlabelled break
give the same correct result. A labelled break becomes essential only when control
must jump out of an outer loop from inside a nested one — e.g. if the requirement had
instead been “stop the entire scan the moment any item anywhere is out of stock,”
only break aisleLoop; could achieve that.
[6/6 marks]
Page 7
Java Programming — Answer Script Group D
3. [Theory] Class, Object, Method & Encapsulation
(a) Discuss the difference between a class, an object, and a method.
Basis Class Object Method
Definition A blueprint/template A real instance of a class, A block of code inside a
defining fields and created in memory with class defining one specific
behaviours for a category actual field values. action/behaviour.
of things.
Memory No memory until Occupies heap memory; Code exists in class area;
instantiated (logical only). created with 'new'. executes only when
invoked.
Keyword class new returnType
methodName(...)
Analogy Blueprint of a car. An actual car built from An action the car can do,
the blueprint. e.g. accelerate().
class Car { // CLASS - blueprint
String color;
void accelerate() { // METHOD - a behaviour
[Link]("Car is accelerating");
}
}
public class Test {
public static void main(String[] args) {
Car myCar = new Car(); // OBJECT - real instance
[Link] = "Red";
[Link](); // calling the method on the object
}
}
[8/8 marks]
(b) Explain how encapsulation is achieved through private fields and public
methods, with a Java code example.
Encapsulation is the OOP principle of binding data (fields) and the code that operates
on that data (methods) together into a single unit (class), while hiding the internal
state from the outside world. In Java it is achieved by declaring fields as private so
they cannot be accessed directly from outside the class, and providing public getter
and setter methods as the only controlled entry points to read or modify those fields.
Page 8
Java Programming — Answer Script Group D
class BankAccount {
private double balance; // private field - hidden from outside
public double getBalance() { // public getter
return balance;
}
public void deposit(double amt) { // public setter with validation
if (amt > 0) {
balance += amt;
} else {
[Link]("Invalid deposit amount");
}
}
}
public class Test {
public static void main(String[] args) {
BankAccount acc = new BankAccount();
// [Link] = 5000; // NOT ALLOWED - compile error (private)
[Link](5000); // allowed only through public method
[Link]("Balance: " + [Link]());
}
}
Because balance is private, it can only be changed through deposit(), which validates the
amount first. This protects data integrity and is the key benefit of encapsulation.
[7/7 marks]
Page 9
Java Programming — Answer Script Group D
4. [Theory] Constructors & the 'this' keyword
(a) Explain default and parameterized constructors in Java with suitable
examples.
A constructor is a special member that has the same name as the class, no return
type, and runs automatically when an object is created with new, to initialise the
object.
• Default constructor: takes no arguments; initialises fields to fixed/default values,
or is auto-generated by Java if no constructor is written at all.
• Parameterized constructor: takes one or more arguments so each object can be
initialised with different, caller-supplied values.
class Student {
String name;
int marks;
Student() { // default constructor
name = "Not Assigned";
marks = 0;
}
Student(String n, int m) { // parameterized constructor
name = n;
marks = m;
}
}
public class Test {
public static void main(String[] args) {
Student s1 = new Student(); // uses default constructor
Student s2 = new Student("Bindhu", 95); // uses parameterized constructor
[Link]([Link] + " - " + [Link]);
[Link]([Link] + " - " + [Link]);
}
}
Not Assigned - 0
Bindhu - 95
[8/8 marks]
(b) Describe the role of the 'this' keyword in constructor chaining, with a
Java code example.
this is a reference to the current object. In constructor chaining, this(...) is used as
the first statement of one constructor to call another constructor of the same class,
avoiding duplicate initialisation code. It can also be used as [Link] to distinguish
an instance field from a parameter of the same name.
Page 10
Java Programming — Answer Script Group D
class Student {
String name;
int marks;
String grade;
Student(String name, int marks) {
[Link] = name; // '[Link]' = field, 'name' = parameter
[Link] = marks;
[Link] = "Not Computed";
}
Student(String name, int marks, String grade) {
this(name, marks); // CONSTRUCTOR CHAINING - calls constructor above
[Link] = grade; // then adds the extra initialisation
}
}
public class Test {
public static void main(String[] args) {
Student s = new Student("Bindhu", 95, "A+");
[Link]([Link] + " " + [Link] + " " + [Link]);
}
}
Bindhu 95 A+
this(...) must always be the first line of the constructor; it lets the 3-argument constructor
reuse the 2-argument constructor's logic instead of repeating it.
[7/7 marks]
Page 11
Java Programming — Answer Script Group D
5. [Program] Ride-hailing fare system — inheritance, super, method
overriding
(a) Vehicle base class with Bike, Car, Auto subclasses overriding fare
calculation using 'super'.
class Vehicle {
double baseFare = 30.0; // fixed base fare, common to all
double calculateFare(double km) {
return baseFare; // default: only base fare
}
}
class Bike extends Vehicle {
double calculateFare(double km) {
return [Link](km) + (km * 8); // base fare + per-km rate
}
}
class Car extends Vehicle {
double calculateFare(double km) {
return [Link](km) + (km * 15);
}
}
class Auto extends Vehicle {
double calculateFare(double km) {
return [Link](km) + (km * 11);
}
}
public class RideFareSystem {
public static void main(String[] args) {
Vehicle bike = new Bike();
Vehicle car = new Car();
Vehicle auto = new Auto();
double distance = 10; // sample distance in km
[Link]("Bike fare (" + distance + " km): Rs. " + [Link](distance));
[Link]("Car fare (" + distance + " km): Rs. " + [Link](distance));
[Link]("Auto fare (" + distance + " km): Rs. " + [Link](distance));
}
}
Explanation: Each subclass overrides calculateFare() to apply its own per-km rate,
but first calls [Link](km) to reuse the base fare logic from Vehicle
instead of duplicating it — this is the correct use of super to extend, not replace,
inherited behaviour.
[9/9 marks]
(b) Extend the program to display the final fare for a sample 10 km ride for
each of the three vehicle types.
Page 12
Java Programming — Answer Script Group D
// Add this loop in main() to summarise all three fares neatly:
Vehicle[] rides = { new Bike(), new Car(), new Auto() };
String[] names = { "Bike", "Car", "Auto" };
double km = 10;
[Link]("---- Fare Summary for 10 km ride ----");
for (int i = 0; i < [Link]; i++) {
[Link](names[i] + " -> Rs. " + rides[i].calculateFare(km));
}
---- Fare Summary for 10 km ride ----
Bike fare (10.0 km): Rs. 110.0
Car fare (10.0 km): Rs. 180.0
Auto fare (10.0 km): Rs. 140.0
---- Fare Summary for 10 km ride ----
Bike -> Rs. 110.0
Car -> Rs. 180.0
Auto -> Rs. 140.0
Calculation check (10 km): Bike = 30 + 10×8 = 110; Car = 30 + 10×15 = 180; Auto =
30 + 10×11 = 140. Storing objects in a Vehicle[] array and calling the same method
on each demonstrates runtime polymorphism: the correct overridden version runs for
each object automatically.
[6/6 marks]
--- END OF ANSWERS ---
Page 13