Java Question Bank
Java Question Bank
Topics Covered:
Operators • If-Else • Loops • Arrays • String Methods • Methods • OOP’s •
Collections
PART 1 — QUIZ QUESTIONS
DAY 1: Operators
A) 10
B) 5
C) 15
D) 50
Answer: C) 15
Explanation: '+=' is the add-assignment operator. x becomes 10+5 = 15.
A) =
B) ==
C) equals()
D) !=
Answer: B) ==
Explanation: '==' compares primitive values. In Java, '=' is assignment.
Q4. What is the output of: boolean hasTicket = true; boolean hasId = false;
[Link](hasTicket && hasId);
A) true
B) false
C) 1
D) 0
Answer: B) false
Explanation: AND requires both operands to be true. hasId is false, so result is false.
Q5. In a hotel PIN system, you check enteredPin == correctPin. What type of
operator is '=='?
A) Assignment
B) Comparison
C) Logical
D) Arithmetic
Answer: B) Comparison
Explanation: == is a comparison/relational operator that evaluates to a boolean.
A) 13
B) 10
C) 3
D) 7
Answer: D) 7
Explanation: '-=' subtracts the right-hand value. 10-3 = 7.
A) true
B) false
C) 1
D) 0
Answer: B) false
Explanation: '!' is the logical NOT operator; it inverts the boolean value.
A) 4
B) 3
C) 12
D) 7
Answer: C) 12
Explanation: '*=' multiplies and assigns: 4 * 3 = 12.
Q10. A student needs both an ID card AND a hall ticket to enter an exam. Which
operator models this?
A) ||
B) !
C) &&
D) ==
Answer: C) &&
Explanation: Both conditions must be true — logical AND (&&).
Q11. What is the output: int a=5; int b=5; [Link](a != b);
A) true
B) false
C) 5
D) 0
Answer: B) false
Explanation: '!=' checks if values are not equal. Since a==b, result is false.
A) +=
B) -=
C) ==
D) *=
Answer: C) ==
Explanation: '==' is a comparison operator, not an assignment operator.
A) 10
B) 2
C) 5
D) 8
Answer: C) 5
Explanation: '/=' divides and assigns: 10/2 = 5.
A) false
B) true
C) 10
D) 0
Answer: B) true
Explanation: '>=' checks if left is greater than OR equal to right. 10 >= 10 is true.
A) ==
B) !=
C) =
D) >=
Answer: C) =
Explanation: '=' assigns the right-hand value to the left-hand variable.
A) false
B) 3
C) 5
D) true
Answer: D) true
Explanation: '<' checks if 3 is less than 5, which is true.
Q19. An ATM checks if balance >= withdrawal amount. Which operator is used?
A) ==
B) <=
C) >=
D) >
Answer: C) >=
Explanation: We need to confirm balance is sufficient — greater than or equal check.
A) Checks equality
B) Checks inequality
C) Assigns a value
D) Logical AND
Answer: B) Checks inequality
Explanation: '!=' returns true if the two operands are NOT equal.
A) 8
B) 3
C) 2
D) 5
Answer: C) 2
Explanation: '%=' computes remainder: 8 % 3 = 2.
A) &&
B) ||
C) !
D) !=
Answer: C) !
Explanation: '!' inverts the boolean: !true = false, !false = true.
A) false
B) true
C) 0
D) 1
Answer: B) true
A) >
B) <
C) <=
D) >=
Answer: B) <
Explanation: '<' checks strict less-than. Under 18 qualifies.
A) true
B) false
C) 5
D) 4
Answer: B) false
Explanation: 5 is not less than or equal to 4, so false.
If-Else Statements
Q1. A student has marks=35. What does 'if (marks >= 40)' evaluate to?
A) true
B) false
C) 35
D) Compile error
Answer: B) false
Explanation: 35 is not >= 40, so the condition is false and the if-block is skipped.
A) Only 1
B) Only 2
C) As many as needed
D) None
Answer: C) As many as needed
Explanation: Java allows unlimited else-if chaining to handle multiple conditions.
Q4. A voter eligibility check: age=20. What prints?if(age>=18) print 'Can vote';
else print 'Cannot vote';
A) Cannot vote
B) Can vote
C) 20
D) Nothing
Answer: B) Can vote
Explanation: 20 >= 18 is true, so 'Can vote' is printed.
A) An if inside a loop
B) An if inside another if
C) An if with many else-if
D) An if without else
A) A
B) B
C) C
D) D
Answer: B) B
Explanation: 75 fails the first condition (>=90) but satisfies >=75, so grade B.
A) or
B) elif
C) else if
D) otherwise
Answer: C) else if
Explanation: Java uses 'else if' (two words) for chaining alternative conditions.
Q8. int temp=15; if(temp>30) print 'Hot'; else if(temp>20) print 'Warm'; else
print 'Cold'; — output?
A) Hot
B) Warm
C) Cold
D) 15
Answer: C) Cold
Explanation: 15 fails both conditions, so 'Cold' is printed.
A) Enter
B) Too young to watch
C) No ticket
D) Compile error
Answer: B) Too young to watch
Explanation: hasTicket passes, but age 12 < 18 fails the inner check.
Q10. Can an if statement exist without an else?
Q12. int x=0; if(x>0) print 'Positive'; else if(x<0) print 'Negative'; else print 'Zero';
— output?
A) Positive
B) Negative
C) Zero
D) Nothing
Answer: C) Zero
Explanation: x=0 fails both first conditions, so the final else executes.
A) if x > 5 { }
B) if (x > 5) { }
C) if [x > 5] { }
D) if x > 5 then { }
Answer: B) if (x > 5) { }
Explanation: Java requires the condition to be in parentheses.
Q14. In a bank loan system, salary >= 30000 AND age >= 21 must both be true.
Which structure?
A) if with ||
B) Nested if or if with &&
C) Only else
D) switch
Answer: B) Nested if or if with &&
Explanation: Two conditions that must both be true: use && or nest the ifs.
Q15. What is the output: int a=5; if(a==5) { if(a>3) print 'Yes'; } else print 'No';
A) No
B) Yes
C) 5
D) Compile error
Answer: B) Yes
Explanation: a==5 is true, then a>3 is also true, so 'Yes' prints.
A) Yes always
B) No, it skips remaining conditions
C) Only for int types
D) Only with nested ifs
Answer: B) No, it skips remaining conditions
Explanation: Once a condition is true and its block executes, all remaining else/else-if blocks are
skipped.
Q17. int age=17; if(age>=18) print 'Adult'; else print 'Minor'; — output?
A) Adult
B) Minor
C) 17
D) Nothing
Answer: B) Minor
Explanation: 17 is not >= 18, so else-block executes.
A) default
B) finally
C) else
D) catch
Answer: C) else
Explanation: The final 'else' acts as the default fallback.
A) a>5
B) a>0
C) Both simultaneously
D) Neither
Answer: B) a>0
Explanation: Java evaluates conditions top-to-bottom; a>0 is checked first.
A) Access Denied
B) Access Granted
C) abc123
D) Compile error
Answer: B) Access Granted
Explanation: The strings match, so equals() returns true and the if-block runs.
A) Yes
B) No, it must follow an if
C) Only in Java 8+
D) Only in loops
Answer: B) No, it must follow an if
Explanation: else if must always follow an if or another else-if.
Q23. int marks=40; if(marks>=40) print 'Pass'; else print 'Fail'; — output?
A) Fail
B) Pass
C) 40
D) Nothing
Answer: B) Pass
Explanation: marks==40 satisfies >=40, so 'Pass' is printed.
Q24. In an e-commerce discount system: purchase>=5000 gets 20% off,
>=2000 gets 10% off, else no discount. Which structure models this?
A) Only if
B) switch
C) if-else-if chain
D) Nested for loop
Answer: C) if-else-if chain
Explanation: Multiple exclusive ranges with one matching outcome fit the if-else-if structure perfectly.
Q25. What is the output: if(false) print 'A'; else if(false) print 'B'; else print 'C';
A) A
B) B
C) C
D) Nothing
Answer: C) C
Explanation: Both conditions are false, so the final else-block prints 'C'.
DAY 2: Loops
Q1. Which loop is best when we know how many times to repeat?
A) while
B) do-while
C) for
D) foreach
Answer: C) for
Explanation: The for-loop is designed for a fixed number of iterations with built-in init, condition, and
update.
A) 0
B) 1
C) 2
D) Depends on the condition
Answer: B) 1
Explanation: do-while checks the condition AFTER the block executes, guaranteeing at least one
execution.
Q3. for(int i=1; i<=3; i++) — how many times does the loop run?
A) 2
B) 3
C) 4
D) 1
Answer: B) 3
Explanation: i starts at 1, runs while i<=3, increments. Iterations: i=1, 2, 3.
Q5. In the attendance roll call example, which loop type is used to print roll
numbers 1 to 5?
A) while
B) do-while
C) for
D) forEach
Answer: C) for
Explanation: Calling attendance from 1 to 5 (known count) uses a for-loop.
Q6. int bottles=1; while(bottles<=5) { print; bottles++; } — how many bottles are
printed?
A) 4
B) 5
C) 6
D) 1
Answer: B) 5
Explanation: Loop runs while bottles<=5: iterations for 1,2,3,4,5 — five times.
Q7. What is the output of a do-while with attempts=1, runs while attempts<=3?
A) Prints once
B) Prints 3 times
C) Prints 4 times
D) Never prints
Answer: B) Prints 3 times
Explanation: Runs for attempts=1,2,3 — three times total.
A) Condition
B) Update
C) Initialization
D) Body
Answer: C) Initialization
Explanation: The initialization section (e.g., int i=0) runs exactly once before the loop begins.
Q12. for(int i=0; i<5; i++) — what is the last value of i when the condition first
fails?
A) 4
B) 5
C) 6
D) 0
Answer: B) 5
Explanation: When i becomes 5, the condition 5<5 is false and the loop stops.
Q13. A supermarket checks items until the cart is empty. Which loop fits best?
A) for
B) do-while
C) while
D) forEach
Answer: C) while
Explanation: Cart emptying is condition-driven (unknown item count) — while is ideal.
Q14. What is the update expression in: for(int i=0; i<10; i+=2)?
A) int i=0
B) i<10
C) i+=2
D) i
Answer: C) i+=2
Explanation: The third part of the for-loop header is the update expression.
Q15. An ATM prompts for a PIN at least once, then re-prompts if wrong. Best loop?
A) for
B) while
C) do-while
D) nested for
Answer: C) do-while
Explanation: Prompting at least once, then repeating on failure = do-while pattern.
Q16. int sum=0; for(int i=1; i<=4; i++) sum+=i; — what is sum?
A) 4
B) 10
C) 6
D) 16
Answer: B) 10
Explanation: 1+2+3+4 = 10.
Q17. A nested loop with outer i from 1 to 3 and inner j from 1 to 3 — how
many total iterations?
A) 3
B) 6
C) 9
D) 12
Answer: C) 9
Explanation: 3 outer × 3 inner = 9 total iterations.
A) for-loop
B) for-each loop
C) while-loop
D) do-while loop
Answer: B) for-each loop
Explanation: The enhanced for (for-each) loop iterates directly over elements of an array or
collection.
Q19. Which loop structure guarantees the loop body runs before checking the
condition?
A) for
B) while
C) do-while
D) for-each
Answer: C) do-while
Explanation: do-while executes the body first, then evaluates the condition.
A) 5
B) 0
C) 1
D) 4
Answer: C) 1
Explanation: Loop decrements i: 5,4,3,2,1 — last printed is 1 (when i becomes 0, loop stops).
A) Initialization
B) Condition
C) Update
D) Method call
Answer: D) Method call
Explanation: A for-loop header has three sections: initialization; condition; update. Method calls
belong in the body.
Q22. Calling each friend's name from a list one by one — best loop?
A) while
B) for with index
C) for-each
D) do-while
Answer: C) for-each
Explanation: Iterating through all elements without needing the index is the for-each pattern.
A) Decrements i by 1
B) Multiplies i by 2
C) Increments i by 1
D) Resets i to 0
Answer: C) Increments i by 1
Explanation: i++ is the post-increment operator: adds 1 to i after the current iteration.
Q24. A game replays a level until the player wins. Which loop?
A) for
B) while
C) do-while
D) none
Answer: C) do-while
Explanation: The level plays at least once, then repeats if the player loses — do-while.
Q25. for(int i=1; i<=5; i++) if(i==3) continue; — how many numbers are printed?
A) 5
B) 4
C) 3
D) 2
Answer: B) 4
Explanation: continue skips printing when i==3. So 1,2,4,5 are printed — 4 numbers.
DAY 3: Arrays
A) 85
B) 90
C) 78
D) 3
Answer: B) 90
Explanation: Array indices start at 0. marks[0]=85, marks[1]=90.
A) [Link]()
B) [Link]()
C) [Link]
D) [Link]()
Answer: C) [Link]
Explanation: The 'length' property (not a method) returns the number of elements.
Q4. Which loop is best for printing every element of an array without needing the
index?
A) for
B) while
C) for-each
D) do-while
Answer: C) for-each
Explanation: For-each (enhanced for) iterates over elements directly when the index isn't needed.
Q5. int[] prices = new int[3]; — how many elements can this store?
A) 2
B) 3
C) 4
D) 0
Answer: B) 3
Explanation: 'new int[3]' creates an array with 3 elements (indices 0,1,2).
A) null
B) 1
C) 0
D) -1
Answer: C) 0
Explanation: Java initializes numeric array elements to 0 by default.
A) 45
B) 89
C) 92
D) 78
Answer: C) 92
Explanation: By iterating and comparing, 92 is the largest value.
A) 5
B) 4
C) 0
D) 3
Answer: B) 4
Explanation: Last index = length - 1 = 5-1 = 4.
Q11. In a shopping bill program, prices = {120.0, 45.5, 230.0}. To get total, you:
A) Yes
B) No, all elements must be the same type
C) Yes, using Object[]
D) Only in ArrayList
Answer: B) No, all elements must be the same type
Explanation: A Java array is typed — all elements must match the declared type.
A) 2
B) 3
C) 4
D) 1
Answer: B) 3
Explanation: The array has 3 elements, so [Link] = 3.
A) Static array
B) Dynamic array
C) ArrayList
D) LinkedList
Answer: A) Static array
Explanation: 'new int[5]' creates a fixed-size array — its size cannot change after creation.
Q16. for(int i=0; i<[Link]; i++) — what does [Link] control here?
A) 1
B) 0
C) -1
D) Depends on declaration
Answer: B) 0
Explanation: Java arrays are 0-indexed; the first element is always at index 0.
A) 20
B) 10
C) 0
D) null
Answer: C) 0
Explanation: Unassigned int array positions default to 0.
Q19. How would you store a list of 30 students' names entered from keyboard?
A) Indices of scores
B) Values of scores one by one
C) Only the first element
D) Random elements
Answer: B) Values of scores one by one
Explanation: The for-each loop assigns each element's value to 'score' in turn.
A) Returns 0
B) Returns null
C) ArrayIndexOutOfBoundsException
D) Compile error
Answer: C) ArrayIndexOutOfBoundsException
Explanation: Index 5 is out of bounds for a 5-element array (valid: 0-4).
A) 1
B) 4
C) 5
D) 3
Answer: C) 5
Explanation: Index 4 is the 5th element: {3(0),1(1),4(2),1(3),5(4)}.
Q24. Which is the correct way to update the first element of int[] prices to 500?
A) prices(0) = 500;
B) prices[1] = 500;
C) prices[0] = 500;
D) [Link](0, 500);
Q25. A grocery app needs to find the cheapest product from an array of prices.
Which approach?
A) 4
B) 5
C) 6
D) 3
Answer: B) 5
Explanation: 'Rahul' has 5 characters: R-a-h-u-l.
Q2. String s = " hello "; [Link](); — what does trim() do?
A) Hyderabad
B) HYDERABAD
C) hyderabad
D) HyDeRaBaD
Answer: B) HYDERABAD
Explanation: toUpperCase() converts every character to its uppercase equivalent.
A) USER@[Link]
B) user@[Link]
C) User@[Link]
D) unchanged
Answer: B) user@[Link]
Explanation: toLowerCase() converts all characters to lowercase.
A) 0
B) 5
C) 6
D) 4
Answer: C) 6
Explanation: L(0)e(1)a(2)r(3)n(4) (5)J(6) — 'Java' starts at index 6.
A) RaviKumar
B) Ravi Kumar
C) Kumar Ravi
D) Ravi+Kumar
Answer: B) Ravi Kumar
Explanation: concat() appends strings. fn + space + ln = 'Ravi Kumar'.
A) Reference equality
B) Case-insensitive equality
C) Exact character-by-character equality
D) Length equality
Answer: C) Exact character-by-character equality
Explanation: equals() compares character by character, case-sensitively.
A) false
B) true
C) abc123
D) 1
Answer: B) true
Explanation: Both strings have identical characters, so equals() returns true.
A) true
B) false
C) Hello
D) hello
Answer: B) false
Explanation: equals() is case-sensitive; 'H' != 'h'.
A) String
B) char
C) double
D) int
Answer: D) int
Explanation: length() returns an int representing the count of characters.
A) 4
B) 5
C) 6
D) 7
Answer: B) 5
Explanation: J(0)a(1)v(2)a(3) (4)P(5) — 'Program' starts at index 5.
A) join()
B) merge()
C) concat()
D) append()
Answer: C) concat()
Explanation: concat() appends one string to the end of another.
A) HELLO
B) Hello
C) hello
D) hElLo
Answer: C) hello
Explanation: toLowerCase() converts every uppercase character to lowercase.
Q15. In a login form, a user enters ' admin ' with extra spaces. Which method
cleans it?
A) toUpperCase()
B) concat()
C) indexOf()
D) trim()
Answer: D) trim()
Explanation: trim() removes leading and trailing whitespace from user input.
A) 0
B) null
C) -1
D) false
Answer: C) -1
Explanation: indexOf() returns -1 when the specified substring does not exist in the string.
A) 5
B) 6
C) 7
D) 4
Answer: B) 6
Explanation: A-n-j-a-l-i = 6 characters.
A) lower()
B) toLower()
C) toLowerCase()
D) shrink()
Answer: C) toLowerCase()
Explanation: toLowerCase() is the Java String method for lowercase conversion.
Q19. For a username field, you want to normalise to lowercase before saving to
DB. Which method?
A) trim()
B) toLowerCase()
C) equals()
D) indexOf()
Answer: B) toLowerCase()
Explanation: Normalising input to lowercase before storage ensures consistent comparison.
A) 5
B) 6
C) 7
D) 4
Answer: B) 6
Explanation: h(0)e(1)l(2)l(3)o(4) (5)w(6) — 'world' starts at index 6.
A) false
B) true
C) Pass
D) null
Answer: B) true
Explanation: Identical strings return true from equals().
A) void
B) int
C) A new combined String
D) char
Answer: C) A new combined String
Explanation: Strings are immutable; concat() returns a new String object.
A) 8
B) 6
C) 4
D) 10
Answer: C) 4
Explanation: trim() removes spaces → "Java" → length = 4.
Q24. A search feature finds the position of a keyword in an article. Which method?
A) length()
B) equals()
C) indexOf()
D) trim()
Answer: C) indexOf()
Explanation: indexOf() returns the position of a substring within a string.
A) false
B) true
C) HELLO
D) hello
Answer: B) true
Explanation: HELLO → toLowerCase → hello; [Link](hello) = true.
DAY 4: Methods
A) A variable
B) A block of code that performs a task and can be called by name
C) A loop
D) A data type
Answer: B) A block of code that performs a task and can be called by name
Explanation: A method groups reusable logic under a name.
A) Return method
B) Void parameterized method
C) Void non-parameterized method
D) Static return method
Answer: C) Void non-parameterized method
Explanation: void = no return, no parameters = non-parameterized.
A) null
B) return
C) void
D) empty
Answer: C) void
Explanation: The 'void' keyword declares that a method does not return any value.
Q4. public static int addTwoNumbers(int a, int b) — what does this method return?
A) void
B) String
C) int
D) double
Answer: C) int
Explanation: The return type 'int' before the method name specifies what it returns.
Q7. public static String getSchoolName() { return "ABC School"; } — return type?
A) void
B) int
C) String
D) char
Answer: C) String
Explanation: The return type declared before the method name is String.
A) printWelcome[];
B) call printWelcome();
C) printWelcome();
D) invoke printWelcome;
Answer: C) printWelcome();
Explanation: Static methods are called directly by name followed by parentheses.
Q9. What are the values inside parentheses when calling a method called?
A) Return values
B) Parameters
C) Arguments
D) Variables
Answer: C) Arguments
Explanation: Values passed to a method during a call are called arguments.
A) send
B) give
C) return
D) output
Answer: C) return
Explanation: 'return' exits the method and optionally sends a value to the caller.
A) No
B) Yes, but only 'return;' with no value
C) Yes, with any value
D) Only in Java 11+
Answer: B) Yes, but only 'return;' with no value
Explanation: A void method can use bare 'return;' to exit early.
Q13. public static void printMenu() — this method takes how many arguments?
A) 1
B) 0
C) unknown
D) 2
Answer: B) 0
Explanation: Empty parentheses mean no parameters.
Q18. What happens if you call a method with the wrong number of arguments?
A) public
B) private
C) static
D) protected
Answer: C) static
Explanation: Static methods belong to the class, not to instances, so no object is needed.
Q21. A calculator app reuses the same addition logic in multiple screens. Best
practice?
A) Copy-paste the code
B) Create a method add(int a, int b)
C) Use a loop
D) Use an array
Answer: B) Create a method add(int a, int b)
Explanation: Encapsulate reusable logic in a method to avoid duplication.
A) 3
B) 7
C) 37
D) 10
Answer: D) 10
Explanation: 3+7=10 is returned and printed.
A) No
B) Yes
C) Only same class methods
D) Only void methods
Answer: B) Yes
Explanation: Methods can call any accessible method, enabling modular design.
A) 1
B) 2
C) 3
D) 4
Answer: C) 3
Explanation: name, id, salary — three parameters.
DAY 5: Collections
A) HashSet
B) TreeSet
C) ArrayList
D) HashMap
Answer: C) ArrayList
Explanation: ArrayList is an ordered, duplicate-allowing List implementation.
A) HashSet
B) LinkedHashSet
C) TreeSet
D) ArrayList
Answer: C) TreeSet
Explanation: TreeSet stores elements sorted in their natural (ascending) order.
A) HashMap
B) TreeMap
C) LinkedHashMap
D) HashSet
Answer: C) LinkedHashMap
Explanation: LinkedHashMap preserves the order in which keys were inserted.
A) Single value
B) Key-value pair
C) Sorted set
D) Linked node only
Answer: B) Key-value pair
Explanation: HashMap stores data as key-value pairs.
A) 1
B) 2
C) 0
D) Error
Answer: B) 2
Explanation: ArrayList allows duplicates, so both 'Ravi' entries are stored.
Q6. Which collection should you use to store unique phone numbers with no order
requirement?
A) ArrayList
B) LinkedList
C) HashSet
D) TreeMap
Answer: C) HashSet
Explanation: HashSet stores unique values with no guaranteed order.
A) [Link](key)
B) [Link](key)
C) [Link](key)
D) [Link](key)
Answer: A) [Link](key)
Explanation: HashMap's get() method returns the value associated with the specified key.
A) ArrayList
B) TreeList
C) LinkedList
D) HashList
Answer: C) LinkedList
Explanation: LinkedList uses a doubly-linked structure, making add/remove O(1) at front/back.
A) import [Link];
B) import [Link];
C) import [Link];
D) import [Link];
Answer: B) import [Link];
Explanation: ArrayList is in the [Link] package.
A) Insertion order
B) Random order
C) Natural ascending order
D) Descending order
Answer: C) Natural ascending order
Explanation: TreeMap sorts keys in their natural order (ascending for integers).
Q13. A hotel menu needs items in the order they were added. Best Map?
A) HashMap
B) TreeMap
C) LinkedHashMap
D) HashSet
Answer: C) LinkedHashMap
Explanation: LinkedHashMap maintains key insertion order — ideal for ordered menus.
A) HashMap
B) TreeMap
C) LinkedHashMap
D) LinkedList
Answer: D) LinkedList
Explanation: LinkedList implements List and Deque, not Map.
Q15. How do you add an element to an ArrayList?
A) [Link]()
B) [Link]()
C) [Link]()
D) [Link]()
Answer: B) [Link]()
Explanation: ArrayList's add() method appends an element to the list.
A) 4
B) 3
C) 2
D) 1
Answer: B) 3
Explanation: HashSet rejects the duplicate 90, storing 90, 75, 60 — size 3.
Q17. Which is the best collection for a task list where tasks are added/removed
from front?
A) ArrayList
B) HashMap
C) LinkedList
D) TreeSet
Answer: C) LinkedList
Explanation: LinkedList's addFirst()/removeFirst() are O(1) — ideal for queue/deque patterns.
A) Removes a key
B) Returns the value
C) Checks if a key exists
D) Sorts the map
Answer: C) Checks if a key exists
Explanation: containsKey() returns true if the map contains the specified key.
A) 66,45,92
B) 92,66,45
C) 45,66,92
D) Random
Answer: C) 45,66,92
Explanation: TreeSet auto-sorts in ascending natural order.
A) TreeMap
B) Hashtable
C) HashMap
D) TreeSet
Answer: C) HashMap
Explanation: HashMap allows one null key and multiple null values. TreeMap does not.
A) ArrayList
B) HashSet
C) HashMap<String,Integer>
D) TreeSet
Answer: C) HashMap<String,Integer>
Explanation: HashMap maps each word (key) to its count (value) efficiently.
A) [Link]()
B) [Link]() in a for-each
C) [Link]()
D) [Link]()
Answer: B) [Link]() in a for-each
Explanation: keySet() returns a Set of all keys, which can be iterated with for-each.
Q23. Which collection is best for storing visited web pages in visit order without
duplicates?
A) ArrayList
B) HashSet
C) TreeSet
D) LinkedHashSet
Answer: D) LinkedHashSet
Explanation: LinkedHashSet: unique + insertion order — perfect for ordered visited pages.
A) No difference
B) ArrayList uses an array; LinkedList uses nodes with pointers
C) ArrayList is unordered; LinkedList is ordered
D) ArrayList allows duplicates; LinkedList does not
Answer: B) ArrayList uses an array; LinkedList uses nodes with pointers
Explanation: ArrayList has fast random access; LinkedList has fast insert/delete.
Q25. A leaderboard must show top scores in descending order. Which collection
helps?
A) HashSet
B) ArrayList with [Link]()
C) TreeMap
D) LinkedList
Answer: B) ArrayList with [Link]()
Explanation: Store scores in ArrayList, then sort descending with
[Link]([Link]()).
PART 2 — REAL-WORLD CODING SCENARIOS
Each scenario presents a real-world problem and a complete Java solution using the topics from the
repository.
DAY 1: Operators
Output:
Access granted. Dispensing Rs.5000
Real-World Context:
Students must carry both their ID card and hall ticket to enter an exam hall. The
system checks both conditions before allowing entry.
Task:
Use the logical AND operator to enforce both conditions.
Solution:
public class ExamHallEntry {
public static void main(String[] args) {
boolean hasIdCard = true;
boolean hasHallTicket = false;
boolean canEnter = hasIdCard && hasHallTicket;
if (canEnter) {
[Link]("Entry allowed. Good luck!");
} else {
[Link]("Entry denied. Missing document.");
[Link]("ID Card: " + hasIdCard);
[Link]("Hall Ticket: " + hasHallTicket);
}
}
}
Output:
Entry denied. Missing document.
ID Card: true
Hall Ticket: false
Output:
Purchase: Rs.3500.0
Discount: Rs.350.0
Final Amount: Rs.3150.0
If-Else Statements
Scenario 4: Movie Ticket Age Gate
Real-World Context:
A cinema multiplex allows entry for adult movies only to people aged 18 or above. For
those with tickets below 18, it prints a different message.
Task:
Use nested if-else to check ticket possession first, then age.
Solution:
public class MovieTicketGate {
public static void main(String[] args) {
boolean hasTicket = true;
int age = 16;
int minAge = 18;
if (hasTicket) {
if (age >= minAge) {
[Link]("Welcome! Enjoy the movie.");
} else {
[Link]("Sorry, you must be " + minAge + "+ to watch.");
}
} else {
[Link]("No ticket found. Please buy one.");
}
}
}
Output:
Sorry, you must be 18+ to watch.
Real-World Context:
A school generates grade cards automatically based on percentage: A (≥90), B (≥75),
C (≥60), D (≥45), F (below 45).
Task:
Use an if-else-if chain to assign the correct grade.
Solution:
public class GradeCard {
public static void main(String[] args) {
int marks = 72;
String grade;
Output:
Marks: 72
Grade: C
Solution:
public class LoanEligibility {
public static void main(String[] args) {
double salary = 35000.0;
int age = 28;
if (salary >= 30000 && age >= 21 && age <= 60)
{ [Link]("Loan approved! Welcome.");
} else {
[Link]("Loan not approved.");
if (salary < 30000)
[Link]("Reason: Salary below threshold.");
if (age < 21 || age > 60)
[Link]("Reason: Age not in eligible range.");
}
}
}
Output:
Loan approved! Welcome.
DAY 2: Loops
Solution:
public class AttendanceRollCall {
public static void main(String[] args) {
int absentRoll = 15;
Output:
Roll 1 : Present
...
Roll 15 : ABSENT
Roll 16 : Present
...
Real-World Context:
A factory filling machine fills bottles one by one. It keeps filling as long as fewer than
10 bottles are filled, then displays a completion message.
Task:
Use a while-loop to model the filling process.
Solution:
public class BottleFilling {
public static void main(String[] args) {
int filledBottles = 0;
int targetBottles = 10;
Solution:
public class OTPVerification {
public static void main(String[] args) {
int correctOTP = 4829;
int enteredOTP = 0;
int attempts = 0;
int maxAttempts = 3;
boolean verified = false;
do {
enteredOTP = userInputs[attempts];
attempts++;
[Link]("Attempt " + attempts + ": Entered OTP = " +
enteredOTP);
if (enteredOTP == correctOTP)
{ verified = true;
[Link]("OTP Verified! Login successful.");
}
} while (!verified && attempts < maxAttempts);
Output:
Attempt 1: Entered OTP = 1111
Attempt 2: Entered OTP = 2222
Attempt 3: Entered OTP = 4829
OTP Verified! Login successful.
Real-World Context:
A student practice app generates the multiplication table for any number from 1 to 10.
Task:
Output:
Multiplication Table of 7:
7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70
Arrays
Solution:
public class MarksAnalysis {
public static void main(String[] args) {
int[] marks = {72, 85, 91, 60, 78};
int highest = marks[0];
int lowest = marks[0];
int sum = 0;
Output:
Highest: 91
Lowest : 60
Average: 77.2
Solution:
public class ShoppingBill {
public static void main(String[] args) {
double[] prices = {120.50, 45.00, 230.75, 89.99, 310.00};
double total = 0;
double budget = 700.0;
Output:
--- Shopping Bill ---
Item 1: Rs.120.5
...
Total: Rs.796.24
Over budget by Rs.96.24
Solution:
public class ClassTopper {
public static void main(String[] args) {
String[] names = {"Ravi", "Anjali", "Kiran", "Priya", "Arjun"};
int[] scores = { 82, 95, 78, 90, 88 };
int topperIndex = 0;
for (int i = 1; i < [Link]; i++)
{ if (scores[i] > scores[topperIndex])
{
topperIndex = i;
}
}
Output:
Class Topper: Anjali
Score: 95
DAY 3: String Methods
Solution:
public class RegistrationValidation {
public static void main(String[] args) {
String username = "john_doe";
String email = "john@[Link]";
String password = "pass1234";
Output:
Username valid : true
Email valid : true
Password valid : true
Registration successful!
Solution:
public class EmployeeIDCard {
public static void main(String[] args)
{ String name = " ravi kumar ";
String department = "software engineering";
String empId = "EMP-2024-007";
String cleanName = [Link]().toUpperCase();
String cleanDept = [Link]().toUpperCase();
String displayLine = "Name: ".concat(cleanName)
.concat(" | Dept: ").concat(cleanDept)
.concat(" | ID: ").concat(empId);
Output:
====== EMPLOYEE ID CARD ======
Name: RAVI KUMAR | Dept: SOFTWARE ENGINEERING | ID: EMP-2024-007
Solution:
public class LoginAuthentication {
public static void main(String[] args) {
String storedUsername = "Admin";
String storedPassword = "SecurePass123";
Output:
Login successful. Welcome, Admin!
DAY 4: Methods
Solution:
public class RestaurantBill {
Output:
Table: T-01
Subtotal: Rs.450.0
Tax (5%): Rs.22.5
Total: Rs.472.5
Solution:
public class TemperatureConverter {
Output:
37.0°C = 98.6°F
98.6°F = 37.0°C
DAY 5: Collections
Solution:
import [Link];
// Add students
[Link](101, "Ravi Kumar");
[Link](102, "Anjali Sharma");
[Link](103, "Kiran Reddy");
[Link](104, "Priya Singh");
// Search
[Link]("Roll 102: " + [Link](102));
// Update
[Link](103, "Kiran Reddy Naidu");
// Remove
[Link](104);
// Display all
[Link]("\n--- Student Directory ---");
for (int roll : [Link]()) {
[Link](roll + " -> " + [Link](roll));
}
Output:
Roll 102: Anjali Sharma
Solution:
import [Link];
Output:
Unique visitors today:
1. user_101
2. user_205
3. user_330
4. user_412
Total unique visits: 4
Real-World Context:
A store manager wants to see all products sorted by price (TreeMap sorts by key).
Products are keyed by price for quick sorted display.
Task:
Use TreeMap<Double, String> to maintain price-sorted inventory.
Solution:
import [Link];
Output:
--- Products (Low to High Price) ---
Rs.199.0 - Pen Drive (16GB)
Rs.499.0 - USB Cable
...
Cheapest: 199.0 - Pen Drive (16GB)
Solution:
import [Link];
[Link]("Current Tasks:");
for (String t : tasks) [Link](" - " + t);
Output:
Current Tasks:
- Fix production bug #1031
- Write unit tests
- Code review PR-42
- Update documentation
Real-World Context:
A text analysis tool reads a sentence and counts how many times each word appears.
Task:
Use HashMap<String,Integer> to count word frequencies.
Solution:
import [Link];
[Link]("Word Frequencies:");
for (String w : [Link]()) {
[Link](w + " : " + [Link](w));
}
}
}
Output:
Word Frequencies:
java : 3
is : 2
great : 1
fun : 1
Solution:
import [Link];
Output:
===== REPORT CARD =====
Ravi -> 82 | Grade: B
Anjali -> 95 | Grade: A
Kiran -> 67 | Grade: C
Priya -> 55 | Grade: D
Class Topper: Anjali (95)
END OF STUDY GUIDE
175 Quiz Questions • 24 Real-World Coding Scenarios
Topics: Operators | If-Else | Loops | Arrays | String Methods | Methods | Collections
DAY 4 — OOP CONCEPTS
Object-Oriented Programming — Quiz & Real-World Coding Scenarios
Topics: Classes & Objects • Constructors • Inheritance • Polymorphism • Encapsulation
• Abstraction • Interfaces • Keywords
A) A keyword
B) A real-world entity created from a class
C) A method
D) A data type
Q3. In the repo example: OopStudent student = new OopStudent(); — what does
'new' do?
A) Imports a library
B) Declares a variable
C) Allocates memory and creates an object
D) Calls a static method
A) create
B) object
C) new
D) make
Answer: C) new
Explanation: The 'new' keyword instantiates (creates) an object from a class.
A) null
B) OopStudent
C) Rahul
D) name
Answer: C) Rahul
Explanation: Assigning "Rahul" to [Link] sets that field on this specific object instance.
Q6. What is the term for variables defined inside a class (like name, age)?
A) Local variables
B) Parameters
C) Fields / Instance variables
D) Static variables
A) Only 1
B) Only 2
C) Unlimited
D) Depends on memory only
Answer: C) Unlimited
Explanation: A class is a template; you can create as many objects as needed from it.
Q8. In a school system, which is the class and which is the object?'Student' and
'Ravi'
A) Both are objects
B) Student is the class; Ravi is the object
C) Ravi is the class; Student is the object
D) Both are classes
A) A field
B) A class
C) A method / behaviour of the object
D) A constructor
Q11. What is the default value of a String field in a class if not assigned?
A) ""
B) 0
C) false
D) null
Answer: D) null
Explanation: Java sets reference-type fields (including String) to null if not explicitly initialised.
Q12. Which statement correctly creates a Car object from a Car class?
A) Car = new();
B) Car myCar;
Q13. If OopStudent has fields name and age, how many copies of those fields does
each object get?
A) Classes
B) Methods
C) Objects / Instances
D) Constructors
A) Yes
B) No
C) Only static fields
D) Only in the same package
Answer: B) No
Explanation: Private fields are hidden from outside the class. They must be accessed via public
methods.
A) Inheritance
B) Association
C) Composition
D) Overloading
Answer: B) Association
Explanation: When one class uses objects of another class, it is called association (or composition if
ownership is implied).
Q19. A 'BankAccount' class has fields accountNumber and balance, and methods
deposit() and withdraw(). What are deposit() and withdraw() called?
A) Fields
B) Constructors
C) Behaviours / Methods
D) Attributes
A) Ravi
B) null
C) Empty string
D) Same as [Link]
Answer: B) null
Explanation: s1 and s2 are separate objects. Changing [Link] does not affect [Link].
Answer: B) A class naturally bundles data (fields) and behaviour (methods) together
Explanation: One of OOP's core ideas is that a class packages data and the operations on that data
together.
Q22. In the repo, class OopStudent has a void display() method. Why is it void?
A) It returns an int
B) It accepts parameters
C) It does not return any value
D) It is abstract
Q23. An e-commerce app has a 'Product' class. Each product listed on the site is a
.
A) Class
B) Method
C) Object / Instance
D) Package
A) It stays forever
B) The programmer must delete it
C) The Garbage Collector reclaims it
D) It becomes a static field
Q25. A class has a method void greet(). If you call [Link](); — what
does student refer to?
A) The class name
B) The method name
C) The object reference
D) The return value
A) void
B) int
C) Same as class name
D) No return type at all
A) A static method
B) The constructor OopEmployee(String, int)
C) The display() method
D) The main() method
Answer: B) To distinguish the instance field from the parameter with the same name
Explanation: Without 'this', Java would assign the parameter to itself. '[Link]' explicitly targets
the field.
Q8. In the repo, OopDog constructor output is: 'Animal constructor' then 'Dog
constructor'. Why?
Answer: A) Dog constructor calls super() which runs Animal constructor first
Explanation: super() is the first statement in OopDog(); it delegates to OopAnimal() before Dog's own
code.
A) No
B) Yes — constructor overloading
C) Only if they have different names
D) Only in abstract classes
Q12. What is the output of: new OopDog(); where OopDog calls super() then prints
'Dog constructor'?
A) Dog constructor
B) Animal constructor
C) Animal constructor\nDog constructor
D) Compile error
Q14. In a Vehicle class, [Link]() is called in a Car subclass. What does this do?
Q15. An Employee constructor sets name and salary via parameters. This ensures:
D) A local variable
Q18. Which line correctly uses super to access a parent class field named 'type' in
a child?
A) type = super
B) [Link]
C) super(type)
D) [Link]
Answer: B) [Link]
Explanation: [Link] accesses a field from the parent class.
Q19. A student registration form requires name, rollNo, and branch at creation
time. The best approach is:
Q20. Can 'this' and 'super' both appear in the same constructor?
A) No
B) Yes, but this() or super() must be the first statement — not both
C) They are identical
D) Only in abstract classes
Answer: B) Yes, but this() or super() must be the first statement — not both
Explanation: Only one of this() or super() can be the first statement; both cannot appear as first
statements simultaneously.
Q21. In the repo, OopEmployee has fields name and salary set via constructor.
Calling [Link]() prints them. What makes this work without setters?
A) The fields are public
B) The constructor directly assigns the values
C) The class is abstract
D) Java defaults them
Answer: B) Instance field and local variable/parameter with the same name
Explanation: When a parameter name shadows a field name, '[Link]' disambiguates.
Q24. A Laptop class has a constructor Laptop(String brand, int ram, double
price). How would you create a Laptop object for Dell, 16GB, ₹75000?
A) new Laptop();
B) new Laptop("Dell", 16, 75000.0);
C) [Link]("Dell",16,75000);
D) Laptop(Dell, 16, 75000)
Q25. In the Animal → Dog hierarchy from the repo, if Dog does NOT call super(),
what happens?
A) OopAnimal constructor is still called
B) OopAnimal constructor is NOT called
C) Compile error always
D) Java calls it automatically last
Explanation: Without super(), only the Dog constructor code runs. However, Java implicitly calls
super() if you omit it (for no-arg parents). If parent has no no-arg constructor, it is a compile error.
Topic 10: Inheritance & Polymorphism
Answer: B) A child class acquiring properties and methods from a parent class
Explanation: Inheritance (IS-A relationship) lets a subclass reuse and extend the parent's members.
A) implements
B) inherits
C) extends
D) super
Answer: C) extends
Explanation: 'class OopCar extends OopVehicle' — 'extends' establishes the inheritance relationship.
Q3. From the repo: OopCar extends OopVehicle. OopCar object calls [Link]().
Where is start() defined?
A) OopCar
B) main method
C) OopVehicle (parent)
D) A separate utility class
Answer: C) @Override
Explanation: @Override tells the compiler to verify that this method actually overrides a parent
method.
Answer: B) Same method name, different parameter list in the same class
Explanation: Overloading is compile-time polymorphism: the method chosen depends on the
arguments passed.
Q8. In OopCalculator: add(int a, int b) and add(int a, int b, int c). How does
Java decide which to call?
A) Randomly
B) By the order they are defined
C) By the number of arguments passed
D) By the return type
A) Runtime polymorphism
B) Dynamic polymorphism
C) Compile-time (static) polymorphism
D) Interface polymorphism
A) Compile-time polymorphism
B) Static polymorphism
C) Runtime (dynamic) polymorphism
D) Constructor polymorphism
A) No
B) Yes, any non-private, non-final parent method can be overridden
C) Only static methods
D) Only abstract methods
A) musicSystem() is private
B) Vehicle does not have musicSystem(); only Car does
C) Vehicle is abstract
Q14. Multiple banks (SBI, HDFC, ICICI) each override interestRate() differently. This
demonstrates:
A) Encapsulation
B) Inheritance + Runtime Polymorphism
C) Static methods
D) Composition
A) Composition
B) Inheritance
C) Encapsulation
D) Association
Answer: B) Inheritance
Explanation: IS-A means: Car IS-A Vehicle. This is how we identify inheritance relationships.
Answer: B) OopMobile
Explanation: OopSamsung IS-A OopMobile — OopSamsung is a specific type of OopMobile.
Q18. In a logistics app: Truck, Van, Bike all extend Vehicle and override deliver().
Calling [Link]() on each gives different output. This is:
A) Method overloading
B) Constructor chaining
C) Runtime polymorphism via overriding
D) Abstraction
Q19. Can the child class add new methods not in the parent?
A) No
B) Yes
C) Only if the parent is abstract
D) Only static methods
Answer: B) Yes
Explanation: OopCar adds musicSystem() which OopVehicle does not have. Subclasses freely
extend functionality.
A) No difference
B) Overloading = same class, different params; Overriding = child class redefines
parent method
C) Overloading is runtime; Overriding is compile-time
D) Overloading uses interfaces
Answer: B) Overloading = same class, different params; Overriding = child class
redefines parent method
Explanation: Overloading happens within one class; overriding happens across a parent-child class
hierarchy.
A) public
B) protected
C) private
D) final
Answer: D) final
Explanation: final methods cannot be overridden. final classes cannot be extended.
Q22. From the repo OopCalculator: add(10, 20) returns 30; add(10, 20, 30) returns
60. This shows:
A) Method overriding
B) Method overloading
C) Constructor chaining
D) Static binding
Q23. An animal shelter app has Animal class with makeSound(). Dog, Cat,
Parrot all override makeSound(). This pattern is called:
A) Method overloading
B) Constructor overloading
C) Polymorphism via method overriding
D) Encapsulation
Q25. In the repo, OopDog extends OopAnimal. OopDog can use methods from
OopAnimal directly. This benefit is called:
A) Encapsulation
B) Abstraction
C) Code reuse via inheritance
D) Interface implementation
A) Extending a class
B) Hiding implementation details
C) Binding data and methods while restricting direct access to data
D) Implementing an interface
Answer: C) Binding data and methods while restricting direct access to data
Explanation: Encapsulation wraps fields (private) and exposes them via controlled public methods
(getters/setters).
A) To make it faster
B) To prevent it being read or changed directly from outside the class
C) To allow inheritance
D) To make it static
Answer: B) To prevent it being read or changed directly from outside the class
Explanation: Private access ensures the PIN can only be changed through validated setPin()
method.
A) interface
B) extends
C) abstract
D) final
Answer: C) abstract
Explanation: 'abstract class OopMobile' — the abstract keyword marks the class and/or its methods
as abstract.
A) Yes
B) No — abstract classes cannot be instantiated
C) Only with 'new abstract'
D) Only from the same package
Answer: C) Concrete
Explanation: A class that implements all abstract methods and can be instantiated is a concrete
class.
Answer: B) A contract that defines what a class must do, without providing how
Explanation: An interface declares method signatures. Implementing classes provide the actual
behaviour.
A) extends
B) inherits
C) implements
D) uses
Answer: C) implements
Explanation: 'class OopGooglePay implements OopPayment' — 'implements' links the class to the
interface contract.
Q11. In the repo, OopPayment interface has void pay(). OopGooglePay implements
it. What must OopGooglePay do?
A) No
B) Yes, separated by commas: implements A, B
C) Only if both interfaces are in the same package
D) Only abstract classes can
Answer: B) Abstract class can have constructors and concrete methods; interface
(pre-Java 8) has only abstract methods
Explanation: Abstract classes support partial implementation; interfaces define pure contracts
(default methods added in Java 8).
Q14. What does the 'static' keyword mean for a class variable?
Q15. From the repo: two OopCollegeStudent objects both print the same
college name. Why?
A) Makes it static
B) Makes it private
C) Prevents the variable's value from being changed after assignment
D) Makes it global
Answer: C) Prevents the variable's value from being changed after assignment
Explanation: final int ticketPrice = 50 — trying to reassign it causes a compile error.
Q17. In the repo, OopBusTicket has final int ticketPrice = 50. Can you change it
later?
A) Yes, using a setter
B) Yes, by re-assigning
C) No — it is final and cannot be modified
D) Only through inheritance
A) Constructors
B) Keywords that control where class members can be accessed from
C) Loop types
D) Exception types
Answer: B) Keywords that control where class members can be accessed from
Explanation: Access modifiers: public (anywhere), private (same class), protected (package +
subclasses), default (package).
Q21. In the repo, OopBike has OopEngine engine = new OopEngine(); — calling
[Link]() first calls:
A) [Link]()
B) [Link]()
C) [Link]()
D) [Link]()
Answer: B) [Link]()
Explanation: startBike() calls [Link]() first, then prints 'Bike started'.
Q25. An HR system uses a Person abstract class (with abstract getRole()) and
Employee, Manager subclasses each implementing getRole(). This is:
A) Method overloading
B) Composition
C) Abstraction with polymorphism
D) Static variable usage
void display() {
[Link]("Patient ID : " + patientId);
[Link]("Name : " + name);
[Link]("Age : " + age);
[Link]("----------------------------------");
}
}
Output:
===== PATIENT RECORDS =====
Patient ID : P-001
Name : Ravi Kumar
Age : 34
Patient ID : P-002
Name : Anjali Sharma
Age : 28
Real-World Context:
When a new employee joins a company, their details (name, department, salary)
must be captured immediately. Using a parameterised constructor with 'this'
ensures clean, immediate initialisation.
Task:
Use a parameterised constructor with 'this' keyword to initialise employee details.
Solution:
class Employee {
private String name;
private String department;
private double salary;
void showDetails() {
[Link]("Name : " + name);
[Link]("Department : " + department);
[Link]("Salary : Rs." + salary);
[Link]("----------------------------------");
}
}
Output:
===== NEW JOINERS =====
Name : Kiran Reddy
Department : Engineering
Salary : Rs.75000.0
...
Solution:
class Vehicle
{ String
brand; int
year;
Output:
Vehicle created: Toyota (2024)
Car features loaded. GPS: true
Toyota engine started.
Toyota music system ON.
Toyota engine stopped.
Solution:
class BankAccount
{ private String
owner;
private double balance;
Output:
Deposited Rs.5000.0 | Balance: Rs.15000.0
Withdrawn Rs.3000.0 | Balance: Rs.12000.0
Insufficient funds.
Final balance: Rs.12000.0
Section 12: Abstraction & Interfaces
Output:
Google Pay: Rs.1299.0 debited via UPI.
Receipt sent to registered email.
---
Paytm Wallet: Rs.450.0 paid from wallet.
Receipt sent to registered email.
---
Credit Card: Rs.5999.0 charged to card **** 4521.
Receipt sent to registered email.
Solution:
abstract class Phone
{ String brand;
Output:
Samsung Galaxy S24: 200MP Triple Camera.
Samsung Galaxy S24: 5000mAh battery.
Samsung Galaxy S24: Calling feature available.
---
iPhone 15 Pro: 48MP ProRAW Camera.
iPhone 15 Pro: 3274mAh battery.
iPhone 15 Pro: Calling feature available.
Solution:
class UniversityStudent
{ private String name;
private String rollNo;
static String university = "Sri Venkateswara University";
static int studentCount = 0;
void display() {
[Link](rollNo + " | " + name + " | " + university);
}
Solution:
class Kitchen {
String speciality;
class Restaurant
{ String name;
Kitchen kitchen; // HAS-A Kitchen
[Link]("Masala Dosa");
[Link]("Margherita Pizza");
}
}
Output:
Spice Garden received order: Masala Dosa
Kitchen preparing: Masala Dosa [Speciality: South Indian]
Order ready for delivery!
Real-World Context:
A cinema booking app combines all OOP concepts: Movie abstract class (abstraction),
Screen implements Bookable interface (interface), Ticket uses encapsulation for seat
and price, and booking logic uses inheritance + polymorphism. This mirrors the
'Advanced' tasks from the repo's README.
Task:
Build a mini booking system combining classes, inheritance, interfaces, encapsulation,
and static fields.
Solution:
// Interface
interface Bookable {
void book(String customerName);
}
// Abstract class
abstract class Movie {
String title;
final int duration; // in minutes — cannot change
@Override
public void book(String customerName)
{ if (availableSeats > 0) {
availableSeats--; totalBookings+
+;
[Link]("Booking confirmed for " + customerName);
[Link](" Movie: " + title + " | Genre: " + getGenre());
[Link](" Price: Rs." + ticketPrice
+ " | Seats left: " + availableSeats);
[Link](" Duration: " + duration + " mins");
[Link]("---");
} else {
[Link]("Sorry " + customerName + ", houseful!");
}
}
}
[Link]("Ravi");
[Link]("Anjali");
[Link]("Kiran");
[Link]("Priya"); // houseful
Output:
Booking confirmed for Ravi
Movie: RRR | Genre: Action
Price: Rs.250.0 | Seats left: 2
Duration: 182 mins
---
Booking confirmed for Anjali
Movie: RRR | Genre: Action
Price: Rs.250.0 | Seats left: 1
Duration: 182 mins
---
Booking confirmed for Kiran
Price: Rs.250.0 | Seats left: 0
---
Sorry Priya, houseful!
Total bookings today: 3
END OF DAY 4 — OOP CONCEPTS
100 OOP Quiz Questions • 9 Real-World Coding Scenarios
Classes & Objects | Constructors | this & super | Inheritance | Polymorphism | Encapsulation | Abstraction
| Interfaces | static | final | Composition