0% found this document useful (0 votes)
3 views101 pages

Java Question Bank

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views101 pages

Java Question Bank

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA CRT STUDY GUIDE

Campus Recruitment Training — Quiz & Coding Scenarios

Topics Covered:
Operators • If-Else • Loops • Arrays • String Methods • Methods • OOP’s •
Collections
PART 1 — QUIZ QUESTIONS

DAY 1: Operators

Q1. What is the output of: int x = 10; x += 5; [Link](x);

A) 10
B) 5
C) 15
D) 50
Answer: C) 15
Explanation: '+=' is the add-assignment operator. x becomes 10+5 = 15.

Q2. Which operator checks if two values are equal?

A) =
B) ==
C) equals()
D) !=
Answer: B) ==
Explanation: '==' compares primitive values. In Java, '=' is assignment.

Q3. What does the '&&' operator do?

A) Returns true if at least one condition is true


B) Returns true only if BOTH conditions are true
C) Negates a boolean
D) Compares two integers
Answer: B) Returns true only if BOTH conditions are true
Explanation: '&&' is the logical AND operator.

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.

Q6. What is the result of: int a = 10; a -= 3; [Link](a);

A) 13
B) 10
C) 3
D) 7
Answer: D) 7
Explanation: '-=' subtracts the right-hand value. 10-3 = 7.

Q7. What does the '||' operator return?

A) True only when both conditions are true


B) True if at least one condition is true
C) Always false
D) Reverses the condition
Answer: B) True if at least one condition is true
Explanation: '||' is logical OR; it returns true if at least one operand is true.

Q8. What is the output: [Link](!true);

A) true
B) false
C) 1
D) 0
Answer: B) false
Explanation: '!' is the logical NOT operator; it inverts the boolean value.

Q9. int x = 4; x *= 3; — what is x?

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.

Q12. Which of these is NOT an assignment operator?

A) +=
B) -=
C) ==
D) *=
Answer: C) ==
Explanation: '==' is a comparison operator, not an assignment operator.

Q13. int x = 10; x /= 2; — what is x?

A) 10
B) 2
C) 5
D) 8
Answer: C) 5
Explanation: '/=' divides and assigns: 10/2 = 5.

Q14. What does '>' mean?


A) Greater than or equal to
B) Less than
C) Greater than
D) Not equal to
Answer: C) Greater than
Explanation: '>' checks if the left operand is strictly greater than the right.

Q15. [Link](10 >= 10); — output?

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.

Q16. What does '>=' mean?

A) Strictly greater than


B) Greater than or equal to
C) Less than or equal to
D) Not equal
Answer: B) Greater than or equal to
Explanation: '>=' is the greater-than-or-equal comparison operator.

Q17. In Java, which symbol is used for assignment?

A) ==
B) !=
C) =
D) >=
Answer: C) =
Explanation: '=' assigns the right-hand value to the left-hand variable.

Q18. What is the output: [Link](3 < 5);

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.

Q20. What does '!=' do?

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.

Q21. int x = 8; x %= 3; — what is x?

A) 8
B) 3
C) 2
D) 5
Answer: C) 2
Explanation: '%=' computes remainder: 8 % 3 = 2.

Q22. Which logical operator negates a boolean?

A) &&
B) ||
C) !
D) !=
Answer: C) !
Explanation: '!' inverts the boolean: !true = false, !false = true.

Q23. [Link](true || false); — output?

A) false
B) true
C) 0
D) 1
Answer: B) true

Explanation: OR returns true if at least one operand is true.


Q24. A cinema checks age < 18 for children tickets. Which operator?

A) >
B) <
C) <=
D) >=
Answer: B) <
Explanation: '<' checks strict less-than. Under 18 qualifies.

Q25. [Link](5 <= 4); — output?

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.

Q2. Which statement runs the else-block?

A) When the if-condition is true


B) When the if-condition is false
C) Always
D) Never
Answer: B) When the if-condition is false
Explanation: The else-block executes only when the preceding if-condition evaluates to false.

Q3. How many else-if blocks can you chain in Java?

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.

Q5. What is a nested if?

A) An if inside a loop
B) An if inside another if
C) An if with many else-if
D) An if without else

Answer: B) An if inside another if


Explanation: A nested if is an if statement written inside the block of another if statement.

Q6. Marks=75, grading: >=90 A, >=75 B, >=60 C. What grade?

A) A
B) B
C) C
D) D
Answer: B) B
Explanation: 75 fails the first condition (>=90) but satisfies >=75, so grade B.

Q7. What keyword starts an alternative condition check?

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.

Q9. A cinema: hasTicket=true, age=12, minAge=18. Nested if checks ticket first,


then age. Output?

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?

A) No, else is mandatory


B) Yes, else is optional
C) Only for comparisons
D) Only with else if
Answer: B) Yes, else is optional
Explanation: The else-block is always optional in Java.

Q11. What happens if NO condition in an if-else-if chain matches and there's no


else?
A) Exception thrown
B) Nothing executes
C) The first block runs
D) Compile error
Answer: B) Nothing executes
Explanation: If no condition matches and there's no else, no block executes.

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.

Q13. Which is the correct Java syntax?

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.

Q16. Does Java evaluate the else-if if the first if is true?

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.

Q18. What keyword introduces the default case in an if-else chain?

A) default
B) finally
C) else
D) catch
Answer: C) else
Explanation: The final 'else' acts as the default fallback.

Q19. How is else-if different from a nested if?


A) They are identical
B) else-if is chained at the same level; nested if is inside a block
C) else-if is faster
D) Nested if supports more conditions
Answer: B) else-if is chained at the same level; nested if is inside a block
Explanation: else-if chains conditions sequentially; nested if goes deeper into a block.

Q20. Which is checked first in: if(a>0) else if(a>5)?

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.

Q21. A password check: entered='abc123', correct='abc123'.


if([Link](correct)) print 'Access Granted'. Output?

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.

Q22. Can an else-if clause exist without a preceding if?

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.

Q2. How many times does a do-while loop execute at minimum?

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.

Q4. What is an infinite loop?

A) A loop that runs exactly once


B) A loop whose condition never becomes false
C) A loop inside another loop
D) A loop with break
Answer: B) A loop whose condition never becomes false
Explanation: If the loop condition is always true, the loop runs forever (infinite loop).

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.

Q8. Which part of a for-loop runs exactly once at the start?

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.

Q9. What happens when 'break' is encountered in a loop?

A) Skips current iteration


B) Exits the loop entirely
C) Restarts the loop
D) Throws an exception
Answer: B) Exits the loop entirely
Explanation: 'break' immediately terminates the enclosing loop.
Q10. What does 'continue' do inside a loop?

A) Exits the loop


B) Skips the rest of the current iteration
C) Restarts the whole loop
D) Pauses execution
Answer: B) Skips the rest of the current iteration
Explanation: 'continue' skips remaining statements in the current iteration and moves to the next.

Q11. When is a while-loop preferred over a for-loop?

A) When we know the exact count


B) When the count is unknown
C) Never
D) For arrays only
Answer: B) When the count is unknown
Explanation: A while-loop is ideal when iterations depend on a runtime condition, not a known count.

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.

Q18. What type of loop is: for(String name : names)?

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.

Q20. int i=5; while(i>0) { [Link](i); i--; } — what prints last?

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).

Q21. Which section is NOT part of a standard for-loop header?

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.

Q23. What does i++ mean in a for-loop?

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

Q1. What is an array in Java?

A) A variable that stores one value


B) A list of key-value pairs
C) A variable storing multiple values of the same type
D) A resizable collection
Answer: C) A variable storing multiple values of the same type
Explanation: Arrays hold a fixed-size sequence of same-type elements.

Q2. int[] marks = {85,90,78}; — what is marks[1]?

A) 85
B) 90
C) 78
D) 3
Answer: B) 90
Explanation: Array indices start at 0. marks[0]=85, marks[1]=90.

Q3. How do you find the number of elements in an array?

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).

Q6. What is the default value of an uninitialized int array element?

A) null
B) 1
C) 0
D) -1
Answer: C) 0
Explanation: Java initializes numeric array elements to 0 by default.

Q7. int[] scores = {45,78,92,66,89}; — what is the highest score?

A) 45
B) 89
C) 92
D) 78
Answer: C) 92
Explanation: By iterating and comparing, 92 is the largest value.

Q8. What is the index of the LAST element in an array of length 5?

A) 5
B) 4
C) 0
D) 3
Answer: B) 4
Explanation: Last index = length - 1 = 5-1 = 4.

Q9. Which statement correctly declares a String array?

A) String array = new String();


B) String[] names = new String[3];
C) string[] names;
D) Array<String> names;
Answer: B) String[] names = new String[3];
Explanation: Java arrays use [] notation and the 'new' keyword for sized declarations.

Q10. What exception is thrown when accessing an invalid array index?


A) NullPointerException
B) ArrayIndexOutOfBoundsException
C) IllegalArgumentException
D) IndexException
Answer: B) ArrayIndexOutOfBoundsException
Explanation: Accessing index >= length or < 0 throws ArrayIndexOutOfBoundsException.

Q11. In a shopping bill program, prices = {120.0, 45.5, 230.0}. To get total, you:

A) Multiply all prices


B) Sum all prices
C) Find the highest price
D) Sort the prices
Answer: B) Sum all prices
Explanation: Calculate the bill by adding all prices from the array.

Q12. Can an array store different data types in Java?

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.

Q13. What is the output: int[] a={1,2,3}; [Link]([Link]);

A) 2
B) 3
C) 4
D) 1
Answer: B) 3
Explanation: The array has 3 elements, so [Link] = 3.

Q14. Which syntax creates an array and assigns values at once?

A) int[] a = new int[]{};


B) int[] a = {1,2,3};
C) int[] a = [1,2,3];
D) Array a = {1,2,3};
Answer: B) int[] a = {1,2,3};
Explanation: Array initializer shorthand assigns values directly using curly braces.
Q15. A teacher stores marks of 5 students. After reading Scanner input, they use
'new int[5]'. What type is this?

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) The sum of marks


B) The loop bound so we don't go out of bounds
C) The data type
D) The sort order
Answer: B) The loop bound so we don't go out of bounds
Explanation: Using [Link] ensures the loop iterates exactly as many times as there are
elements.

Q17. What is the first index of any Java array?

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.

Q18. int[] nums = new int[4]; nums[0]=10; nums[1]=20; — what is nums[2]?

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) String name; for 30 times


B) String[] names = new String[30]; (Scanner in loop)
C) ArrayList only
D) int[] names = new int[30];
Answer: B) String[] names = new String[30]; (Scanner in loop)
Explanation: Declare a String array of size 30, then use a loop and Scanner to fill it.

Q20. What does 'for(int score : scores)' iterate over?

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.

Q21. An array of 5 int elements uses index 0 to 4. Accessing index 5 causes?

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).

Q22. What is a real-life use case for arrays?

A) Storing a single student's name


B) Storing marks of all students in a class
C) Connecting to a database
D) Sending an email
Answer: B) Storing marks of all students in a class
Explanation: Arrays excel at holding multiple homogeneous values like all students' marks.

Q23. int[] a = {3,1,4,1,5}; — what is a[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);

Answer: C) prices[0] = 500;


Explanation: Arrays use bracket notation to access/update elements by index.

Q25. A grocery app needs to find the cheapest product from an array of prices.
Which approach?

A) Sort and print the last


B) Initialize min to first element, loop and compare
C) Use HashMap
D) Use LinkedList
Answer: B) Initialize min to first element, loop and compare
Explanation: Same logic as finding highest: initialise with first element, loop and compare each.
String Methods

Q1. What does length() return for "Rahul"?

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) Removes all spaces


B) Removes leading and trailing spaces
C) Converts to uppercase
D) Splits the string
Answer: B) Removes leading and trailing spaces
Explanation: trim() removes whitespace from both ends, not from within the string.

Q3. What does toUpperCase() return for "hyderabad"?

A) Hyderabad
B) HYDERABAD
C) hyderabad
D) HyDeRaBaD
Answer: B) HYDERABAD
Explanation: toUpperCase() converts every character to its uppercase equivalent.

Q4. String email="USER@[Link]"; [Link](); — output?

A) USER@[Link]
B) user@[Link]
C) User@[Link]
D) unchanged
Answer: B) user@[Link]
Explanation: toLowerCase() converts all characters to lowercase.

Q5. String msg="Learn Java today"; [Link]("Java"); — output?

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.

Q6. String fn="Ravi"; String ln="Kumar"; [Link](" ").concat(ln); — result?

A) RaviKumar
B) Ravi Kumar
C) Kumar Ravi
D) Ravi+Kumar
Answer: B) Ravi Kumar
Explanation: concat() appends strings. fn + space + ln = 'Ravi Kumar'.

Q7. What does equals() check?

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.

Q8. "abc123".equals("abc123") — output?

A) false
B) true
C) abc123
D) 1
Answer: B) true
Explanation: Both strings have identical characters, so equals() returns true.

Q9. "Hello".equals("hello") — output?

A) true
B) false
C) Hello
D) hello
Answer: B) false
Explanation: equals() is case-sensitive; 'H' != 'h'.

Q10. Which method should be used to compare passwords entered by a user?


A) ==
B) equalsIgnoreCase()
C) equals()
D) compare()
Answer: C) equals()
Explanation: Passwords are case-sensitive; use equals() for exact matching.

Q11. What is the return type of length()?

A) String
B) char
C) double
D) int
Answer: D) int
Explanation: length() returns an int representing the count of characters.

Q12. String s = "Java Programming"; [Link]("Program"); — output?

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.

Q13. Which method joins two strings?

A) join()
B) merge()
C) concat()
D) append()
Answer: C) concat()
Explanation: concat() appends one string to the end of another.

Q14. "HELLO".toLowerCase() — output?

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.

Q16. What does indexOf() return if the substring is NOT found?

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.

Q17. String name="Anjali"; [Link]() — output?

A) 5
B) 6
C) 7
D) 4
Answer: B) 6
Explanation: A-n-j-a-l-i = 6 characters.

Q18. Which method makes all characters lowercase?

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.

Q20. "hello world".indexOf("world") — output?

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.

Q21. Which returns true: "Pass".equals("Pass")?

A) false
B) true
C) Pass
D) null
Answer: B) true
Explanation: Identical strings return true from equals().

Q22. What does [Link]() return?

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.

Q23. " Java ".trim().length() — output?

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.

Q25. String s="HELLO"; [Link]().equals("hello") — output?

A) false
B) true
C) HELLO
D) hello
Answer: B) true
Explanation: HELLO → toLowerCase → hello; [Link](hello) = true.
DAY 4: Methods

Q1. What is a method in Java?

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.

Q2. Which method type has no parameters and no return value?

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.

Q3. What keyword indicates a method returns nothing?

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.

Q5. Where is a method's return type specified?

A) After the method name


B) Inside the parentheses
C) Before the method name
D) After the closing brace

Answer: C) Before the method name


Explanation: Return type appears before the method name: returnType methodName(...).

Q6. What is method overloading?

A) Calling a method in a loop


B) Having multiple methods with the same name but different parameters
C) A method calling itself
D) A method inside another method
Answer: B) Having multiple methods with the same name but different parameters
Explanation: Overloading allows same-name methods differentiated by parameter type/count.

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.

Q8. How do you call a static method 'printWelcome' from main?

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.

Q10. A method printStudentDetails(String name, int marks) — how many


parameters?
A) 1
B) 2
C) 3
D) 0
Answer: B) 2
Explanation: name and marks are two parameters.

Q11. What keyword is used to send a value back from a method?

A) send
B) give
C) return
D) output
Answer: C) return
Explanation: 'return' exits the method and optionally sends a value to the caller.

Q12. Can a void method have a return statement?

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.

Q14. What is the advantage of using methods?

A) Makes code longer


B) Avoids repetition and promotes reuse
C) Uses more memory
D) Slows execution
Answer: B) Avoids repetition and promotes reuse
Explanation: Methods encapsulate logic once and allow it to be called multiple times.

Q15. int result = addTwoNumbers(10, 20); — what is result?


A) 10
B) 20
C) 30
D) 200
Answer: C) 30
Explanation: The method adds two numbers: 10+20=30.

Q16. What is a non-parameterized method?

A) A method without a return type


B) A method with no parameters
C) A method inside a class
D) A private method
Answer: B) A method with no parameters
Explanation: Non-parameterized means the method's parentheses are empty — no input needed.

Q17. In a school system, getSchoolName() returns the school name. This is an


example of?
A) void parameterized method
B) non-parameterized return method
C) Constructor
D) Overriding
Answer: B) non-parameterized return method
Explanation: No parameters, but it returns a String value.

Q18. What happens if you call a method with the wrong number of arguments?

A) The extras are ignored


B) A compile-time error occurs
C) A runtime error occurs
D) null is used
Answer: B) A compile-time error occurs
Explanation: Java is strictly typed; argument count and types must match the method signature.

Q19. public static double calculateArea(double radius) — what is the parameter


name?
A) double
B) static
C) calculateArea
D) radius
Answer: D) radius

Explanation: 'radius' is the parameter name; 'double' is its type.


Q20. Which modifier makes a method callable without creating an object?

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.

Q22. What is the output: [Link](addTwoNumbers(3,7)); where the


method returns a+b?

A) 3
B) 7
C) 37
D) 10
Answer: D) 10
Explanation: 3+7=10 is returned and printed.

Q23. Can a method call another method?

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.

Q24. What is method signature?

A) The return type only


B) The method body

C) The method name and parameter list


D) The access modifier
Answer: C) The method name and parameter list
Explanation: A method's signature = its name + parameter types (used in overloading resolution).

Q25. An HR system has printEmployeeDetails(String name, int id, double salary).


How many parameters?

A) 1
B) 2
C) 3
D) 4
Answer: C) 3
Explanation: name, id, salary — three parameters.
DAY 5: Collections

Q1. Which collection maintains insertion order and allows duplicates?

A) HashSet
B) TreeSet
C) ArrayList
D) HashMap
Answer: C) ArrayList
Explanation: ArrayList is an ordered, duplicate-allowing List implementation.

Q2. Which Set implementation stores elements in natural sorted order?

A) HashSet
B) LinkedHashSet
C) TreeSet
D) ArrayList
Answer: C) TreeSet
Explanation: TreeSet stores elements sorted in their natural (ascending) order.

Q3. Which Map maintains insertion order of keys?

A) HashMap
B) TreeMap
C) LinkedHashMap
D) HashSet
Answer: C) LinkedHashMap
Explanation: LinkedHashMap preserves the order in which keys were inserted.

Q4. In HashMap, what is the structure of each entry?

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.

Q5. ArrayList<String> students = new ArrayList<>(); [Link]("Ravi");


[Link]("Ravi"); — size?

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.

Q7. How do you retrieve a value from a HashMap by key?

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.

Q8. Which List is efficient for frequent insertions/deletions?

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.

Q9. [Link](101, "Ravi"); [Link](102, "Anjali"); [Link](102); —


output?
A) Ravi
B) 101
C) Anjali
D) 102
Answer: C) Anjali
Explanation: Key 102 maps to value 'Anjali'.

Q10. Which collection stores unique values IN insertion order?


A) HashSet
B) TreeSet
C) LinkedHashSet
D) ArrayList
Answer: C) LinkedHashSet
Explanation: LinkedHashSet = HashSet ordering + LinkedList insertion-order preservation.

Q11. What import is needed for ArrayList?

A) import [Link];
B) import [Link];
C) import [Link];
D) import [Link];
Answer: B) import [Link];
Explanation: ArrayList is in the [Link] package.

Q12. TreeMap<Integer,String> stores student records sorted by roll number. What


order are keys in?

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.

Q14. Which is NOT a Map implementation?

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.

Q16. A HashSet<Integer> marks = {90,75,90,60}; — size after adding all?

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.

Q18. What does containsKey() do in a HashMap?

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.

Q19. TreeSet<Integer> scores = new TreeSet<>(); [Link](66);


[Link](45); [Link](92); — iteration order?

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.

Q20. Which collection allows null keys?

A) TreeMap
B) Hashtable
C) HashMap
D) TreeSet
Answer: C) HashMap
Explanation: HashMap allows one null key and multiple null values. TreeMap does not.

Q21. To count word frequency in a document, which collection is best?

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.

Q22. How do you iterate over all keys in a HashMap?

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.

Q24. What is the difference between ArrayList and LinkedList?

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

Scenario 1: ATM PIN Verification


Real-World Context:
An ATM machine asks a customer to enter their 4-digit PIN. The system must
compare the entered PIN with the stored PIN and display whether access is
granted.
Task:
Use comparison and logical operators to verify the PIN.
Solution:
public class ATMPinVerification {
public static void main(String[] args) {
int enteredPin = 4521;
int correctPin = 4521;
int balance = 15000;
int withdrawal = 5000;

boolean isPinCorrect = enteredPin == correctPin;


boolean hasSufficientBalance = balance >= withdrawal;

if (isPinCorrect && hasSufficientBalance) {


[Link]("Access granted. Dispensing Rs." + withdrawal);
} else if (!isPinCorrect)
{ [Link]("Incorrect PIN. Try
again.");
} else {
[Link]("Insufficient balance.");
}
}
}

Output:
Access granted. Dispensing Rs.5000

Scenario 2: Exam Hall Entry Check

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

Scenario 3: E-Commerce Discount Calculator


Real-World Context:
An e-commerce platform applies discounts based on purchase amount: 20% off for
purchases ≥
₹5000, 10% off for ≥ ₹2000, otherwise no discount.
Task:
Use comparison operators and assignment operators to calculate the final price.
Solution:
public class DiscountCalculator {
public static void main(String[] args) {
double purchaseAmount = 3500.0;
double discountRate = 0.0;

if (purchaseAmount >= 5000)


{ discountRate = 0.20;
} else if (purchaseAmount >= 2000) {
discountRate = 0.10;
}

double discount = purchaseAmount * discountRate;


double finalAmount = purchaseAmount - discount;

[Link]("Purchase: Rs." + purchaseAmount);


[Link]("Discount: Rs." + discount);
[Link]("Final Amount: Rs." + finalAmount);
}
}

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.

Scenario 5: Student Grade Card

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;

if (marks >= 90) {


grade = "A";
} else if (marks >= 75)
{ grade = "B";
} else if (marks >= 60)
{ grade = "C";
} else if (marks >= 45)
{ grade = "D";
} else {
grade = "F";
}
[Link]("Marks: " + marks);
[Link]("Grade: " + grade);
}
}

Output:
Marks: 72
Grade: C

Scenario 6: Bank Loan Eligibility


Real-World Context:
A bank approves a personal loan only if the applicant's salary is ≥ ₹30,000 AND age
is between 21 and 60.
Task:
Use logical AND operator and nested if-else to check eligibility.

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

Scenario 7: School Attendance Roll Call


Real-World Context:
A class teacher calls attendance roll numbers from 1 to 30. Each roll number is
announced and any absent student (e.g., roll 15) is flagged.
Task:
Use a for-loop to iterate roll numbers and flag an absent student.

Solution:
public class AttendanceRollCall {
public static void main(String[] args) {
int absentRoll = 15;

for (int roll = 1; roll <= 30; roll++)


{ if (roll == absentRoll) {
[Link]("Roll " + roll + " : ABSENT");
} else {
[Link]("Roll " + roll + " : Present");
}
}
}
}

Output:
Roll 1 : Present
...
Roll 15 : ABSENT
Roll 16 : Present
...

Scenario 8: Water Bottle Filling Machine

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;

while (filledBottles < targetBottles) {


filledBottles++;
[Link]("Filled bottle #" + filledBottles);
}

[Link]("All " + targetBottles + " bottles filled!");


}
}
Output:
Filled bottle #1
...
Filled bottle #10
All 10 bottles filled!

Scenario 9: OTP Verification System


Real-World Context:
A banking app sends an OTP and prompts the user to enter it. The user gets 3
attempts. The first prompt always shows — a do-while is needed.
Task:
Use a do-while loop to ensure at least one OTP entry attempt.

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;

// Simulating user input for demo


int[] userInputs = {1111, 2222, 4829};

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);

if (!verified) [Link]("Account locked after 3 failed


attempts.");
}
}

Output:
Attempt 1: Entered OTP = 1111
Attempt 2: Entered OTP = 2222
Attempt 3: Entered OTP = 4829
OTP Verified! Login successful.

Scenario 10: Multiplication Table Generator

Real-World Context:
A student practice app generates the multiplication table for any number from 1 to 10.
Task:

Use a for-loop to generate the multiplication table.


Solution:
public class MultiplicationTable {
public static void main(String[] args) {
int number = 7;

[Link]("Multiplication Table of " + number + ":");


for (int i = 1; i <= 10; i++) {
[Link](number + " x " + i + " = " + (number * i));
}
}
}

Output:
Multiplication Table of 7:
7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70
Arrays

Scenario 11: Student Marks Analysis


Real-World Context:
A teacher wants to enter marks of 5 students, then display the highest, lowest,
and average marks.
Task:
Use an array to store marks and loops to compute the statistics.

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;

for (int m : marks) {


if (m > highest) highest = m;
if (m < lowest) lowest = m;
sum += m;
}

double average = (double) sum / [Link];


[Link]("Highest: " + highest);
[Link]("Lowest : " + lowest);
[Link]("Average: " + average);
}
}

Output:
Highest: 91
Lowest : 60
Average: 77.2

Scenario 12: Supermarket Shopping Bill


Real-World Context:
A customer buys 5 items. The cashier enters all item prices. The system totals
the bill and checks if the total exceeds a budget.
Task:
Use an array to store prices and a loop to sum them.

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;

[Link]("--- Shopping Bill ---");


for (int i = 0; i < [Link]; i++) {
[Link]("Item " + (i+1) + ": Rs." + prices[i]);
total += prices[i];
}

[Link]("Total: Rs." + total);


if (total > budget) {
[Link]("Over budget by Rs." + (total - budget));
} else {
[Link]("Within budget.");
}
}
}

Output:
--- Shopping Bill ---
Item 1: Rs.120.5
...
Total: Rs.796.24
Over budget by Rs.96.24

Scenario 13: Class Topper Finder


Real-World Context:
At prize distribution, the principal wants to announce the student with the highest
score from a class of students.
Task:
Use parallel arrays for names and scores; find the index of the highest score.

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;
}
}

[Link]("Class Topper: " + names[topperIndex]);


[Link]("Score: " + scores[topperIndex]);
}
}

Output:
Class Topper: Anjali
Score: 95
DAY 3: String Methods

Scenario 14: User Registration Form Validation


Real-World Context:
A registration form validates: username must be 6–15 characters, email must contain
'@', and password must be at least 8 characters.
Task:
Use length(), indexOf(), and equals() to validate the inputs.

Solution:
public class RegistrationValidation {
public static void main(String[] args) {
String username = "john_doe";
String email = "john@[Link]";
String password = "pass1234";

boolean userOk = [Link]() >= 6 && [Link]() <= 15;


boolean emailOk = [Link]("@") != -1;
boolean passOk = [Link]() >= 8;

[Link]("Username valid : " + userOk);


[Link]("Email valid : " + emailOk);
[Link]("Password valid : " + passOk);

if (userOk && emailOk && passOk)


{ [Link]("Registration successful!");
} else {
[Link]("Fix validation errors.");
}
}
}

Output:
Username valid : true
Email valid : true
Password valid : true
Registration successful!

Scenario 15: Employee ID Card Generator


Real-World Context:
An HR system generates a formal ID card display by formatting employee details:
name in uppercase, department in title-trim, joining a full display string.
Task:
Use toUpperCase(), trim(), concat(), and length().

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);

[Link]("====== EMPLOYEE ID CARD ======");


[Link](displayLine);
[Link]("Card length: " + [Link]() + " chars");
}
}

Output:
====== EMPLOYEE ID CARD ======
Name: RAVI KUMAR | Dept: SOFTWARE ENGINEERING | ID: EMP-2024-007

Scenario 16: Login Authentication System


Real-World Context:
A web app authenticates users by comparing entered credentials with stored ones.
Usernames are case-insensitive but passwords are case-sensitive.
Task:
Use equalsIgnoreCase() for username and equals() for password.

Solution:
public class LoginAuthentication {
public static void main(String[] args) {
String storedUsername = "Admin";
String storedPassword = "SecurePass123";

String enteredUsername = "admin";


String enteredPassword = "SecurePass123";

boolean userMatch = [Link](enteredUsername);


boolean passMatch = [Link](enteredPassword);

if (userMatch && passMatch) {


[Link]("Login successful. Welcome, " + storedUsername +
"!");
} else {
[Link]("Invalid credentials. Access denied.");
}
}
}

Output:
Login successful. Welcome, Admin!
DAY 4: Methods

Scenario 17: Restaurant Bill Calculator


Real-World Context:
A restaurant app calculates bills for multiple tables. The same billing logic should be
reused for each table without duplicating code.
Task:
Create methods for calculating subtotal, tax, and total.

Solution:
public class RestaurantBill {

public static double calculateSubtotal(double[] prices) {


double sub = 0;
for (double p : prices) sub += p;
return sub;
}

public static double calculateTax(double subtotal, double taxRate) {


return subtotal * taxRate;
}

public static void printBill(String tableNo, double[] prices)


{ double subtotal = calculateSubtotal(prices);
double tax = calculateTax(subtotal, 0.05);
double total = subtotal + tax;
[Link]("Table: " + tableNo);
[Link]("Subtotal: Rs." + subtotal);
[Link]("Tax (5%): Rs." + tax);
[Link]("Total: Rs." + total);
}

public static void main(String[] args)


{ double[] table1 = {120.0, 250.0, 80.0};
double[] table2 = {350.0, 190.0};
printBill("T-01", table1);
[Link]("------------------");
printBill("T-02", table2);
}
}

Output:
Table: T-01
Subtotal: Rs.450.0
Tax (5%): Rs.22.5
Total: Rs.472.5

Scenario 18: Temperature Converter


Real-World Context:
A weather app converts temperatures between Celsius and Fahrenheit. The same
conversion logic is needed in multiple features.
Task:
Create separate methods for each conversion direction.

Solution:
public class TemperatureConverter {

public static double celsiusToFahrenheit(double celsius)


{ return (celsius * 9.0 / 5.0) + 32;
}

public static double fahrenheitToCelsius(double fahrenheit)


{ return (fahrenheit - 32) * 5.0 / 9.0;
}

public static void main(String[] args) {


double bodyTemp = 37.0;
double roomTemp = 98.6;

[Link](bodyTemp + "°C = " + celsiusToFahrenheit(bodyTemp) +


"°F");
[Link](roomTemp + "°F = " + fahrenheitToCelsius(roomTemp) +
"°C");
}
}

Output:
37.0°C = 98.6°F
98.6°F = 37.0°C
DAY 5: Collections

Scenario 19: University Student Directory


Real-World Context:
A university maintains a directory of students by roll number. The system should add,
search, remove, and display students.
Task:
Use HashMap<Integer, String> to build the student directory.

Solution:
import [Link];

public class StudentDirectory {


public static void main(String[] args) {
HashMap<Integer, String> directory = new HashMap<>();

// 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));
}

[Link]("Total students: " + [Link]());


}
}

Output:
Roll 102: Anjali Sharma

--- Student Directory ---


101 -> Ravi Kumar
102 -> Anjali Sharma
103 -> Kiran Reddy Naidu
Total students: 3

Scenario 20: Unique Visitor Tracker


Real-World Context:
A website tracks unique visitors per day. If the same user visits again, they
should not be counted twice. The order of first visit should be preserved.
Task:
Use LinkedHashSet to store unique visitors in visit order.

Solution:
import [Link];

public class UniqueVisitorTracker {


public static void main(String[] args)
{ LinkedHashSet<String> visitors = new
LinkedHashSet<>();

// Simulating page visits


[Link]("user_101");
[Link]("user_205");
[Link]("user_101"); // revisit - ignored
[Link]("user_330");
[Link]("user_205"); // revisit - ignored
[Link]("user_412");

[Link]("Unique visitors today:");


int count = 1;
for (String visitor : visitors)
{ [Link](count++ + ". " + visitor);
}
[Link]("Total unique visits: " + [Link]());
}
}

Output:
Unique visitors today:
1. user_101
2. user_205
3. user_330
4. user_412
Total unique visits: 4

Scenario 21: Product Inventory with Sorted Prices

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];

public class ProductInventory {


public static void main(String[] args) {
TreeMap<Double, String> inventory = new TreeMap<>();

[Link](499.0, "USB Cable");


[Link](1299.0, "Wireless Mouse");
[Link](199.0, "Pen Drive (16GB)");
[Link](2499.0, "Mechanical Keyboard");
[Link](799.0, "Phone Stand");
[Link]("--- Products (Low to High Price) ---");
for (double price : [Link]()) {
[Link]("Rs." + price + " - " + [Link](price));
}

[Link]("Cheapest: " + [Link]() + " - " +


[Link]([Link]()));
[Link]("Costliest: " + [Link]() + " - " +
[Link]([Link]()));
}
}

Output:
--- Products (Low to High Price) ---
Rs.199.0 - Pen Drive (16GB)
Rs.499.0 - USB Cable
...
Cheapest: 199.0 - Pen Drive (16GB)

Scenario 22: Daily Task Manager


Real-World Context:
A developer's task manager maintains a list of tasks. Tasks can be added to the front
(urgent) or back, and completed tasks are removed.
Task:
Use LinkedList to manage tasks as a queue/deque.

Solution:
import [Link];

public class TaskManager {


public static void main(String[] args)
{ LinkedList<String> tasks = new LinkedList<>();

// Add regular tasks


[Link]("Write unit tests");
[Link]("Code review PR-42");
[Link]("Update documentation");

// Add urgent task to front


[Link]("Fix production bug #1031");

[Link]("Current Tasks:");
for (String t : tasks) [Link](" - " + t);

// Complete first task


String completed = [Link]();
[Link]("\nCompleted: " + completed);

[Link]("Remaining tasks: " + [Link]());


}
}

Output:
Current Tasks:
- Fix production bug #1031
- Write unit tests
- Code review PR-42
- Update documentation

Completed: Fix production bug #1031


Remaining tasks: 3

Scenario 23: Word Frequency Counter

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];

public class WordFrequency {


public static void main(String[] args) {
String sentence = "java is great java is fun java";
String[] words = [Link](" ");

HashMap<String, Integer> freq = new HashMap<>();

for (String word : words) {


if ([Link](word))
{ [Link](word, [Link](word) + 1);
} else {
[Link](word, 1);
}
}

[Link]("Word Frequencies:");
for (String w : [Link]()) {
[Link](w + " : " + [Link](w));
}
}
}

Output:
Word Frequencies:
java : 3
is : 2
great : 1
fun : 1

Combined Scenario — Full Mini Application

Scenario 24: Student Report Card System


Real-World Context:
A school wants a complete report card system: store students and marks, compute
grade using if-else, find class topper using array logic, and display sorted results.
Task:
Combine arrays, loops, if-else, methods, and Collections in one program.

Solution:
import [Link];

public class ReportCardSystem {

public static String getGrade(int marks) {


if (marks >= 90) return "A";
else if (marks >= 75) return "B";
else if (marks >= 60) return "C";
else if (marks >= 45) return "D";
else return "F";
}

public static String findTopper(String[] names, int[] marks)


{ int topIdx = 0;
for (int i = 1; i < [Link]; i++) {
if (marks[i] > marks[topIdx]) topIdx = i;
}
return names[topIdx] + " (" + marks[topIdx] + ")";
}

public static void main(String[] args) {


String[] names = {"Ravi", "Anjali", "Kiran", "Priya"};
int[] marks = {82, 95, 67, 55};

LinkedHashMap<String, String> report = new LinkedHashMap<>();


for (int i = 0; i < [Link]; i++) {
[Link](names[i], marks[i] + " | Grade: " + getGrade(marks[i]));
}

[Link]("===== REPORT CARD =====");


for (String name : [Link]()) {
[Link](name + " -> " + [Link](name));
}
[Link]("Class Topper: " + findTopper(names, marks));
}
}

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

DAY 4 — PART 1: OOP QUIZ QUESTIONS


25 multiple-choice questions per sub-topic, with correct answers highlighted and explanations based on
the repository examples.

Topic 8: Classes & Objects

Q1. What is a class in Java?

A) An object that stores data


B) A blueprint or template for creating objects
C) A loop structure
D) A built-in Java function

Answer: B) A blueprint or template for creating objects


Explanation: A class defines the properties and behaviours that its objects will have.

Q2. What is an object in Java?

A) A keyword
B) A real-world entity created from a class
C) A method
D) A data type

Answer: B) A real-world entity created from a class


Explanation: An object is a specific instance of a class, e.g., student 'Rahul' is an object of the
Student class.

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

Answer: C) Allocates memory and creates an object


Explanation: 'new' allocates heap memory for the object and invokes the constructor.

Q4. Which keyword is used to create an object from a class?

A) create
B) object
C) new
D) make

Answer: C) new
Explanation: The 'new' keyword instantiates (creates) an object from a class.

Q5. Given: OopStudent student = new OopStudent(); [Link] = "Rahul"; —


what is [Link]?

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

Answer: C) Fields / Instance variables


Explanation: Variables declared inside a class but outside methods are called fields or instance
variables.

Q7. How many objects can be created from one class?

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

Answer: B) Student is the class; Ravi is the object


Explanation: Student defines the blueprint; Ravi is a specific real-world instance of that blueprint.

Q9. What does the dot (.) operator do on an object?

A) Creates the object


B) Deletes the object
C) Accesses fields or methods of the object
D) Declares the class

Answer: C) Accesses fields or methods of the object


Explanation: The dot operator (.) is used to access an object's members: [Link],
[Link]().

Q10. [Link](); — what is 'display' here?

A) A field
B) A class
C) A method / behaviour of the object
D) A constructor

Answer: C) A method / behaviour of the object


Explanation: display() is a method defined inside OopStudent that describes what the object can do.

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;

C) Car myCar = new Car();


D) new Car myCar;
Answer: C) Car myCar = new Car();
Explanation: Syntax: ClassName variableName = new ClassName();

Q13. If OopStudent has fields name and age, how many copies of those fields does
each object get?

A) One copy shared by all objects


B) Each object gets its own copy
C) Only the first object gets them
D) No copies — fields are static

Answer: B) Each object gets its own copy


Explanation: Instance fields are per-object. [Link] and [Link] are completely
independent.

Q14. What is the relationship between a class and an object?

A) Class IS-A object


B) Object IS-A class
C) Class is the blueprint; object is the instance
D) They are the same thing

Answer: C) Class is the blueprint; object is the instance


Explanation: This is the fundamental OOP relationship: class defines, object instantiates.

Q15. In a hospital system, 'Patient' is a class. 'patient1', 'patient2' are .

A) Classes
B) Methods
C) Objects / Instances
D) Constructors

Answer: C) Objects / Instances


Explanation: Each patient record is a separate object created from the Patient class blueprint.

Q16. What is the output of: OopStudent s = new OopStudent(); [Link]="Anjali";


[Link]=20; [Link]();where display() prints name and age?

A) Student Name: null


B) Student Name: Anjali, Student Age: 20
C) Anjali 20
D) Error

Answer: B) Student Name: Anjali, Student Age: 20


Explanation: After assigning name and age to the object, calling display() prints them.
Q17. Can an object access private fields of its class directly from outside the class?

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.

Q18. What term describes a class creating objects of another class?

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

Answer: C) Behaviours / Methods


Explanation: Methods represent what an object can do — its behaviours.

Q20. OopStudent s1 = new OopStudent(); OopStudent s2 = new OopStudent();


[Link]="Ravi"; — what is [Link]?

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].

Q21. Which of the following best describes encapsulation's relation to a class?


A) A class cannot be encapsulated
B) A class naturally bundles data (fields) and behaviour (methods) together
C) A class and encapsulation are unrelated
D) Only interfaces support encapsulation

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

Answer: C) It does not return any value


Explanation: void means the method performs an action (printing) but sends nothing back to the
caller.

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

Answer: C) Object / Instance


Explanation: Each individual product (laptop, phone, etc.) is a separate object created from the
Product class.

Q24. What happens to an object's memory when it is no longer referenced in Java?

A) It stays forever
B) The programmer must delete it
C) The Garbage Collector reclaims it
D) It becomes a static field

Answer: C) The Garbage Collector reclaims it


Explanation: Java's Garbage Collector automatically frees heap memory for objects with no active
references.

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

Answer: C) The object reference


Explanation: 'student' is the variable holding a reference to the OopStudent object in heap memory.
Topic 9: Constructors, this & super Keywords

Q1. What is a constructor in Java?

A) A method that returns a value


B) A special method that initialises an object when it is created
C) A loop inside a class
D) A static utility method

Answer: B) A special method that initialises an object when it is created


Explanation: A constructor runs automatically when 'new' is used, setting up the object's initial state.

Q2. What is the name rule for a constructor?

A) Can be any name


B) Must match the class name exactly
C) Must start with 'init'
D) Must be lowercase

Answer: B) Must match the class name exactly


Explanation: Java identifies a constructor by the fact that its name equals the class name.

Q3. What is the return type of a constructor?

A) void
B) int
C) Same as class name
D) No return type at all

Answer: D) No return type at all


Explanation: Constructors have no return type — not even void. This distinguishes them from regular
methods.

Q4. In: OopEmployee emp = new OopEmployee("Arjun", 50000); — what is called


automatically?

A) A static method
B) The constructor OopEmployee(String, int)
C) The display() method
D) The main() method

Answer: B) The constructor OopEmployee(String, int)


Explanation: When 'new' is used, the matching constructor is invoked automatically.
Q5. What does the 'this' keyword refer to?

A) The parent class


B) The current object
C) A static method
D) The main method

Answer: B) The current object


Explanation: 'this' refers to the instance (object) on which the current method or constructor is
running.

Q6. Why is '[Link] = name' used in OopThisStudent(String name)?

A) To call the parent constructor


B) To distinguish the instance field from the parameter with the same name
C) To create a new object
D) To make name static

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.

Q7. What does 'super()' do inside OopDog's constructor?

A) Creates a Dog object


B) Calls the parent class (OopAnimal) constructor
C) Overrides a method
D) Accesses a static field

Answer: B) Calls the parent class (OopAnimal) constructor


Explanation: super() explicitly calls the parent's constructor, ensuring parent initialisation runs first.

Q8. In the repo, OopDog constructor output is: 'Animal constructor' then 'Dog
constructor'. Why?

A) Dog constructor calls super() which runs Animal constructor first


B) Dog constructor is called twice
C) Static blocks run first
D) Java calls parent constructors alphabetically

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.

Q9. If a class has no constructor, Java provides a .


A) Parameterised constructor
B) Static constructor
C) Default (no-arg) constructor
D) Abstract constructor

Answer: C) Default (no-arg) constructor


Explanation: When no constructor is written, Java inserts a public no-argument default constructor
automatically.

Q10. Can a class have multiple constructors?

A) No
B) Yes — constructor overloading
C) Only if they have different names
D) Only in abstract classes

Answer: B) Yes — constructor overloading


Explanation: Java supports constructor overloading: multiple constructors with different parameter
lists.

Q11. OopEmployee("Arjun", 50000) initialises name and salary. This is an example


of:
A) Method overriding
B) Parameterised constructor
C) Static initialisation
D) Default constructor

Answer: B) Parameterised constructor


Explanation: A constructor that accepts arguments to set initial values is called a parameterised
constructor.

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

Answer: C) Animal constructor then Dog constructor


Explanation: super() runs OopAnimal constructor first, printing 'Animal constructor', then 'Dog
constructor'.

Q13. When is 'this()' used (without dot)?


A) To access fields

B) To call another constructor in the same class (constructor chaining)


C) To call a parent method
D) To create a new object

Answer: B) To call another constructor in the same class (constructor chaining)


Explanation: 'this()' calls an overloaded constructor in the same class. It must be the first statement.

Q14. In a Vehicle class, [Link]() is called in a Car subclass. What does this do?

A) Creates a new Car


B) Calls OopVehicle's start() method
C) Overrides start()
D) Makes start() private

Answer: B) Calls OopVehicle's start() method


Explanation: [Link]() calls the parent class version of that method.

Q15. An Employee constructor sets name and salary via parameters. This ensures:

A) The object is always created with valid initial values


B) The class is abstract
C) Inheritance is applied
D) The method is static

Answer: A) The object is always created with valid initial values


Explanation: Parameterised constructors enforce that mandatory data is provided at object creation
time.

Q16. What happens if you define a parameterised constructor but no default


constructor, then call new OopEmployee()?

A) Java uses the parameterised one


B) Compile error — no matching constructor
C) Runtime error
D) An empty object is created

Answer: B) Compile error — no matching constructor


Explanation: Once you define any constructor, Java no longer provides a default. new
OopEmployee() fails.

Q17. In OopThisStudent, '[Link] = name' — what is the left 'name'?


A) The parameter
B) The instance field
C) A static variable

D) A local variable

Answer: B) The instance field


Explanation: '[Link]' refers to the field declared in the class; plain 'name' is the parameter.

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:

A) Set fields after creation


B) Use a parameterised constructor
C) Use a static method
D) Leave fields as null

Answer: B) Use a parameterised constructor


Explanation: Parameterised constructors guarantee all required data is provided the moment an
object is created.

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) The constructor directly assigns the values


Explanation: The constructor assigns employeeName to name and employeeSalary to salary during
object creation.

Q22. What is constructor chaining?

A) A child class calling a parent constructor via super()


B) Calling multiple methods sequentially
C) Using a loop to create objects
D) A constructor calling itself recursively

Answer: A) A child class calling a parent constructor via super()


Explanation: Constructor chaining means a child constructor calls the parent constructor, creating an
initialisation chain.

Q23. 'this' keyword resolves ambiguity between what two things?

A) Class name and method name


B) Instance field and local variable/parameter with the same name
C) Static and non-static fields
D) Two different objects

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)

Answer: B) new Laptop("Dell", 16, 75000.0);


Explanation: Match the constructor's parameter types: String, int, double.

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

Answer: B) OopAnimal constructor is NOT called

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

Q1. What is inheritance in Java?

A) Two classes sharing a name


B) A child class acquiring properties and methods from a parent class
C) Hiding data inside a class
D) Implementing an interface

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.

Q2. Which keyword is used to inherit from a class?

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) OopVehicle (parent)


Explanation: start() is in OopVehicle; OopCar inherits it and can call it directly.

Q4. What is method overriding?

A) Defining the same method name with different parameters


B) A child class providing its own implementation of a parent's method
C) Calling two methods with the same name
D) A method calling itself

Answer: B) A child class providing its own implementation of a parent's method


Explanation: Overriding replaces the parent's behaviour with a child-specific version at runtime.

Q5. What annotation is used above an overridden method in Java?


A) @Inherit
B) @Overload
C) @Override
D) @Super

Answer: C) @Override
Explanation: @Override tells the compiler to verify that this method actually overrides a parent
method.

Q6. From the repo: [Link]() prints 'General interest rate'.


OopSbiBank overrides it to print 'SBI interest rate: 7%'. What prints when
[Link]() is called?
A) General interest rate
B) SBI interest rate: 7%
C) Both messages
D) Error

Answer: B) SBI interest rate: 7%


Explanation: The overridden version in OopSbiBank is called because sbiBank is an OopSbiBank
object.

Q7. What is method overloading?

A) Same method name, different classes


B) Same method name, different parameter list in the same class
C) Two classes with the same method
D) Calling a method twice

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

Answer: C) By the number of arguments passed


Explanation: The compiler uses the number and types of arguments to pick the correct overloaded
version.

Q9. What does 'polymorphism' mean in Java?


A) Many classes
B) One name, many forms (one method/entity behaving differently in different
contexts)
C) Same class, different names
D) Only interfaces
Answer: B) One name, many forms (one method/entity behaving differently in different
contexts) Explanation: Poly = many, morph = form. The same method name behaves differently
based on context.

Q10. Which type of polymorphism is method overloading?

A) Runtime polymorphism
B) Dynamic polymorphism
C) Compile-time (static) polymorphism
D) Interface polymorphism

Answer: C) Compile-time (static) polymorphism


Explanation: Overloading is resolved at compile time based on method signatures.

Q11. Which type of polymorphism is method overriding?

A) Compile-time polymorphism
B) Static polymorphism
C) Runtime (dynamic) polymorphism
D) Constructor polymorphism

Answer: C) Runtime (dynamic) polymorphism


Explanation: Overriding is resolved at runtime based on the actual object type.

Q12. Can a child class override ALL methods of the parent?

A) No
B) Yes, any non-private, non-final parent method can be overridden
C) Only static methods
D) Only abstract methods

Answer: B) Yes, any non-private, non-final parent method can be overridden


Explanation: Non-private, non-final, non-static methods are open for overriding in subclasses.

Q13. OopCar inherits OopVehicle. OopCar also adds musicSystem(). A Vehicle


object cannot call musicSystem(). Why?

A) musicSystem() is private
B) Vehicle does not have musicSystem(); only Car does
C) Vehicle is abstract

D) Car must be static


Answer: B) Vehicle does not have musicSystem(); only Car does
Explanation: Child classes can add new methods not present in the parent. Parent references cannot
see them.

Q14. Multiple banks (SBI, HDFC, ICICI) each override interestRate() differently. This
demonstrates:

A) Encapsulation
B) Inheritance + Runtime Polymorphism
C) Static methods
D) Composition

Answer: B) Inheritance + Runtime Polymorphism


Explanation: Each bank class extends a common Bank class and overrides interestRate() — a
classic OOP pattern.

Q15. Can a class extend more than one class in Java?

A) Yes, using comma: extends A, B


B) No, Java supports only single class inheritance
C) Yes, using interfaces
D) Only abstract classes allow it

Answer: B) No, Java supports only single class inheritance


Explanation: Java does not support multiple inheritance of classes to avoid the diamond problem.
Interfaces fill this gap.

Q16. What is the 'IS-A' relationship?

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.

Q17. OopSamsung extends OopMobile and overrides camera(). OopSamsung IS-A


.
A) Method
B) OopMobile
C) Constructor
D) Interface

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

Answer: C) Runtime polymorphism via overriding


Explanation: The actual type at runtime (Truck/Van/Bike) determines which deliver() runs.

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.

Q20. What is the difference between overloading and overriding?

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.

Q21. Which access modifier PREVENTS a method from being overridden?

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

Answer: B) Method overloading


Explanation: The same method name 'add' works with 2 or 3 arguments — compile-time
polymorphism.

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

Answer: C) Polymorphism via method overriding


Explanation: Each subclass provides its own unique implementation of the parent's makeSound()
method.

Q24. Which is NOT a valid reason to use inheritance?

A) Reuse parent class code


B) Establish IS-A relationship
C) Override behaviour in child
D) Store data in a HashMap

Answer: D) Store data in a HashMap


Explanation: HashMap is a collection tool, unrelated to inheritance. The others are core benefits of
inheritance.

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

Answer: C) Code reuse via inheritance


Explanation: The primary practical benefit of inheritance is that the child class does not need to
rewrite parent logic.
Topic 11: Encapsulation, Abstraction, Interfaces &
Keywords

Q1. What is encapsulation?

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).

Q2. In OopAtm, the pin field is private. Why?

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.

Q3. What is a getter method?

A) A method that sets a field value


B) A method that returns the value of a private field
C) A constructor
D) A static method

Answer: B) A method that returns the value of a private field


Explanation: getPin() returns the private pin — safely exposing it for reading without allowing direct
modification.

Q4. What is a setter method?

A) Returns a field value


B) Deletes an object
C) Updates the value of a private field
D) Calls the parent constructor

Answer: C) Updates the value of a private field


Explanation: setPin(int newPin) allows controlled update of the private pin field.
Q5. What is abstraction in Java?

A) Hiding implementation and showing only functionality to the user


B) Making all methods public
C) Extending multiple classes
D) Storing objects in a list

Answer: A) Hiding implementation and showing only functionality to the user


Explanation: Abstraction = what it does, not how. Users call camera() without knowing the internal
megapixel logic.

Q6. Which keyword creates an abstract class?

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.

Q7. Can you create an object of an abstract class directly?

A) Yes
B) No — abstract classes cannot be instantiated
C) Only with 'new abstract'
D) Only from the same package

Answer: B) No — abstract classes cannot be instantiated


Explanation: Abstract classes are incomplete by design. You must create a concrete subclass to
instantiate.

Q8. OopSamsung extends OopMobile and provides camera(). OopSamsung is


called a
class.
A) Abstract
B) Final
C) Concrete
D) Static

Answer: C) Concrete
Explanation: A class that implements all abstract methods and can be instantiated is a concrete
class.

Q9. What is an interface in Java?


A) A class with only static methods
B) A contract that defines what a class must do, without providing how
C) An abstract class with constructors
D) A collection type

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.

Q10. Which keyword does a class use to implement an interface?

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) Override pay() with its own implementation


B) Leave pay() empty
C) Call [Link]()
D) Declare pay() as static

Answer: A) Override pay() with its own implementation


Explanation: Implementing a class must provide a concrete body for every method in the interface.

Q12. Can a class implement multiple interfaces?

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) Yes, separated by commas: implements A, B


Explanation: Java allows multiple interface implementation — this is how it achieves multiple
inheritance of type.

Q13. What is the difference between abstract class and interface?


A) No difference
B) Abstract class can have constructors and concrete methods; interface (pre-Java
8) has only abstract methods
C) Interface is faster
D) Abstract class uses 'implements'

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?

A) The variable belongs to one specific object


B) The variable is private
C) The variable is shared by ALL objects of the class
D) The variable cannot be changed

Answer: C) The variable is shared by ALL objects of the class


Explanation: static String college = "ABC College" is one copy in memory shared by every
OopCollegeStudent object.

Q15. From the repo: two OopCollegeStudent objects both print the same
college name. Why?

A) They share the same object reference


B) college is a static field — shared by all instances
C) Java copies fields automatically
D) Both call the same constructor

Answer: B) college is a static field — shared by all instances


Explanation: One static variable exists per class, not per object. All objects see the same value.

Q16. What does the 'final' keyword do when applied to a variable?

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

Answer: C) No — it is final and cannot be modified


Explanation: final variables are constants. Once assigned, their value is locked.

Q18. What are access modifiers in Java?

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).

Q19. In OopAccount, balance is private and accessed via showBalance(). This


pattern combines:

A) Inheritance and Polymorphism


B) Encapsulation and Access Modifiers
C) Abstraction and Interfaces
D) Static and Final

Answer: B) Encapsulation and Access Modifiers


Explanation: private field + public method = encapsulation enforced by access modifiers.

Q20. What is composition in OOP?

A) A class extending another


B) A class implementing an interface
C) One class HAS-AN object of another class as a field
D) Two methods with same name

Answer: C) One class HAS-AN object of another class as a field


Explanation: OopBike HAS-AN OopEngine. This is the HAS-A relationship (composition).

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'.

Q22. Composition vs Inheritance — which to use when 'Bike HAS-AN Engine'?

A) Inheritance (Bike extends Engine)


B) Composition (Bike has an Engine object)
C) Interface
D) Static method

Answer: B) Composition (Bike has an Engine object)


Explanation: A Bike IS-NOT-AN Engine; it USES an Engine. HAS-A = composition.

Q23. A PaymentGateway interface is implemented by GPay, Paytm,


AmazonPay. This allows:

A) Multiple objects to be treated uniformly via a common interface


B) Inheritance only
C) Static field sharing
D) Constructor chaining

Answer: A) Multiple objects to be treated uniformly via a common interface


Explanation: Polymorphism via interfaces: any class implementing PaymentGateway can be used
wherever a PaymentGateway is expected.

Q24. Which of the following is TRUE about the 'final' keyword?

A) final class can be extended


B) final method can be overridden
C) final variable can be reassigned
D) final class cannot be extended; final method cannot be overridden; final
variable cannot be reassigned

Answer: D) final class cannot be extended; final method cannot be overridden;


final variable cannot be reassigned
Explanation: final is a lock: on class = no subclassing; on method = no overriding; on variable = no
reassignment.

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

Answer: C) Abstraction with polymorphism


Explanation: Abstract method getRole() is defined once; subclasses provide specific
implementations — abstraction + polymorphism.
DAY 4 — PART 2: OOP REAL-WORLD
CODING SCENARIOS
Each scenario is a complete, runnable Java program drawn from the OOP concepts in the repository,
mapped to real-world business contexts.

Section 9: Classes & Objects

Scenario 25: Hospital Patient Registration


Real-World Context:
A hospital reception desk registers new patients. Each patient has a name, age, and
patientId. The receptionist needs to display the patient details on-screen.
Task:
Create a Patient class with fields and a display() method. Instantiate and display two
patients.
Solution:
class Patient
{ String
patientId; String
name;
int age;

void display() {
[Link]("Patient ID : " + patientId);
[Link]("Name : " + name);
[Link]("Age : " + age);
[Link]("----------------------------------");
}
}

public class HospitalRegistration {


public static void main(String[] args) {
Patient p1 = new Patient();
[Link] = "P-001";
[Link] = "Ravi Kumar";
[Link] = 34;

Patient p2 = new Patient();


[Link] = "P-002";
[Link] = "Anjali Sharma";
[Link] = 28;

[Link]("===== PATIENT RECORDS =====");


[Link]();
[Link]();
}
}

Output:
===== PATIENT RECORDS =====
Patient ID : P-001
Name : Ravi Kumar
Age : 34
Patient ID : P-002
Name : Anjali Sharma
Age : 28

Section 10: Constructors, this & super

Scenario 26: Employee Onboarding System

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;

// Parameterised constructor using 'this'


Employee(String name, String department, double salary) {
[Link] = name;
[Link] = department;
[Link] = salary;
}

void showDetails() {
[Link]("Name : " + name);
[Link]("Department : " + department);
[Link]("Salary : Rs." + salary);
[Link]("----------------------------------");
}
}

public class EmployeeOnboarding {


public static void main(String[] args) {
Employee e1 = new Employee("Kiran Reddy", "Engineering", 75000.0);
Employee e2 = new Employee("Priya Singh", "HR", 55000.0);
Employee e3 = new Employee("Arjun Mehta", "Finance", 65000.0);

[Link]("===== NEW JOINERS =====");


[Link]();
[Link]();
[Link]();
}
}

Output:
===== NEW JOINERS =====
Name : Kiran Reddy
Department : Engineering
Salary : Rs.75000.0
...

Scenario 27: Vehicle Dealership — Inheritance & super


Real-World Context:
A car dealership sells both generic vehicles and specific car models. Cars inherit
common features (start, stop) from Vehicle and extend with their own features
(music system, GPS). The Car constructor calls the Vehicle constructor using super().
Task:
Use extends and super() to model the Vehicle → Car inheritance chain.

Solution:
class Vehicle
{ String
brand; int
year;

Vehicle(String brand, int year)


{ [Link] = brand;
[Link] = year;
[Link]("Vehicle created: " + brand + " (" + year + ")");
}

void start() { [Link](brand + " engine started."); }


void stop() { [Link](brand + " engine stopped."); }
}

class Car extends Vehicle


{ boolean hasGPS;

Car(String brand, int year, boolean hasGPS)


{ super(brand, year); // calls Vehicle constructor
[Link] = hasGPS;
[Link]("Car features loaded. GPS: " + hasGPS);
}

void musicSystem() { [Link](brand + " music system ON."); }


}

public class VehicleDealership {


public static void main(String[] args) {
Car car = new Car("Toyota", 2024, true);
[Link]();
[Link]();
[Link]();
}
}

Output:
Vehicle created: Toyota (2024)
Car features loaded. GPS: true
Toyota engine started.
Toyota music system ON.
Toyota engine stopped.

Section 11: Encapsulation & Access Modifiers


Scenario 28: Bank Account Security System
Real-World Context:
A bank account must protect its balance. Direct access could lead to invalid
states (negative balance). Encapsulation enforces business rules: withdrawals are
only allowed if sufficient balance exists.
Task:
Use private fields with public getters/setters and validation logic inside setter.

Solution:
class BankAccount
{ private String
owner;
private double balance;

BankAccount(String owner, double initialBalance) {


[Link] = owner;
[Link] = initialBalance;
}

public double getBalance() { return balance; }

public void deposit(double amount)


{ if (amount > 0) {
balance += amount;
[Link]("Deposited Rs." + amount
+ " | Balance: Rs." + balance);
}
}

public void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
[Link]("Withdrawn Rs." + amount
+ " | Balance: Rs." + balance);
} else {
[Link]("Insufficient funds.");
}
}
}

public class BankSystem {


public static void main(String[] args) {
BankAccount acc = new BankAccount("Meena", 10000.0);
[Link](5000.0);
[Link](3000.0);
[Link](20000.0);
[Link]("Final balance: Rs." + [Link]());
}
}

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

Scenario 29: Multi-Payment Gateway


Real-World Context:
An e-commerce site supports multiple payment methods: Google Pay, Paytm, and
Credit Card. Each has a different processing logic but must follow the same
contract so the checkout system works uniformly.
Task:
Define a Payment interface; implement it in three classes to demonstrate
polymorphism.
Solution:
interface Payment {
void pay(double amount);
default void receipt() {
[Link]("Receipt sent to registered email.");
}
}

class GooglePay implements Payment {


@Override
public void pay(double amount) {
[Link]("Google Pay: Rs." + amount + " debited via UPI.");
}
}

class Paytm implements Payment {


@Override
public void pay(double amount) {
[Link]("Paytm Wallet: Rs." + amount + " paid from wallet.");
}
}

class CreditCard implements Payment {


@Override
public void pay(double amount) {
[Link]("Credit Card: Rs." + amount + " charged to card ****
4521.");
}
}

public class Checkout {


public static void processPayment(Payment p, double amount) {
[Link](amount);
[Link]();
[Link]("---");
}

public static void main(String[] args)


{ processPayment(new GooglePay(), 1299.0);
processPayment(new Paytm(), 450.0);
processPayment(new CreditCard(), 5999.0);
}
}

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.

Scenario 30: Smartphone Abstraction


Real-World Context:
A mobile app store lists phones from different brands. Each phone has a camera,
battery, and calling feature. Internal hardware details are hidden — users only interact
with the exposed behaviours.
Task:
Use an abstract class Phone with abstract and concrete methods; implement for
Samsung and iPhone.

Solution:
abstract class Phone
{ String brand;

Phone(String brand) { [Link] = brand; }

abstract void camera(); // each brand differs


abstract void batteryInfo(); // each brand differs

void calling() { // common for all


[Link](brand + ": Calling feature available.");
}
}

class Samsung extends Phone {


Samsung() { super("Samsung Galaxy S24"); }

@Override void camera() { [Link](brand + ": 200MP Triple


Camera."); }
@Override void batteryInfo() { [Link](brand + ": 5000mAh
battery."); }
}

class IPhone extends Phone {


IPhone() { super("iPhone 15 Pro"); }

@Override void camera() { [Link](brand + ": 48MP ProRAW


Camera."); }
@Override void batteryInfo() { [Link](brand + ": 3274mAh
battery."); }
}

public class PhoneStore {


public static void showSpecs(Phone p) {
[Link]();
[Link]();
[Link]();
[Link]("---");
}

public static void main(String[] args) {


showSpecs(new Samsung());
showSpecs(new IPhone());
}
}

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.

Section 13: Static, final & Composition

Scenario 31: University Student Counter (static keyword)


Real-World Context:
A university wants to track how many student objects have been created. The counter
should be shared across all objects — not per instance.
Task:
Use a static field to count objects and a static method to display the count.

Solution:
class UniversityStudent
{ private String name;
private String rollNo;
static String university = "Sri Venkateswara University";
static int studentCount = 0;

UniversityStudent(String name, String rollNo) {


[Link] = name;
[Link] = rollNo;
studentCount++; // shared counter increments for every object
}

void display() {
[Link](rollNo + " | " + name + " | " + university);
}

static void showCount() {


[Link]("Total students enrolled: " + studentCount);
}
}

public class UniversitySystem {


public static void main(String[] args) {
UniversityStudent s1 = new UniversityStudent("Ravi", "22CS001");
UniversityStudent s2 = new UniversityStudent("Anjali", "22CS002");
UniversityStudent s3 = new UniversityStudent("Kiran", "22CS003");

[Link](); [Link](); [Link]();


[Link]();
}
}
Output:
22CS001 | Ravi | Sri Venkateswara University
22CS002 | Anjali | Sri Venkateswara University
22CS003 | Kiran | Sri Venkateswara University
Total students enrolled: 3

Scenario 32: Food Delivery App — Composition


Real-World Context:
A food delivery app has Restaurants that own a Kitchen. The Kitchen prepares
food. This is a HAS-A relationship — Restaurant HAS-A Kitchen, not IS-A Kitchen.
Task:
Model composition: Restaurant contains a Kitchen object and delegates cooking to it.

Solution:
class Kitchen {
String speciality;

Kitchen(String speciality) { [Link] = speciality; }

void prepareFood(String item)


{ [Link]("Kitchen preparing: " + item
+ " [Speciality: " + speciality + "]");
}
}

class Restaurant
{ String name;
Kitchen kitchen; // HAS-A Kitchen

Restaurant(String name, String speciality) {


[Link] = name;
[Link] = new Kitchen(speciality);
}

void acceptOrder(String item) {


[Link](name + " received order: " + item);
[Link](item);
[Link]("Order ready for delivery!\n");
}
}

public class FoodDeliveryApp {


public static void main(String[] args) {
Restaurant r1 = new Restaurant("Spice Garden", "South Indian");
Restaurant r2 = new Restaurant("Pizza Hub", "Italian");

[Link]("Masala Dosa");
[Link]("Margherita Pizza");
}
}

Output:
Spice Garden received order: Masala Dosa
Kitchen preparing: Masala Dosa [Speciality: South Indian]
Order ready for delivery!

Pizza Hub received order: Margherita Pizza


Kitchen preparing: Margherita Pizza [Speciality: Italian]
Order ready for delivery!
Section 14: Combined OOP — Full Mini Application

Scenario 33: Online Movie Ticket Booking System

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

Movie(String title, int duration) {


[Link] = title;
[Link] = duration;
}
abstract String getGenre();
}

// Concrete class with encapsulation + implements


class Screen extends Movie implements Bookable {
private int availableSeats;
private double ticketPrice;
static int totalBookings = 0;

Screen(String title, int duration, int seats, double price)


{ super(title, duration);
[Link] = seats;
[Link] = price;
}

@Override public String getGenre() { return "Action"; }

public int getAvailableSeats() { return availableSeats; }


public double getTicketPrice() { return ticketPrice; }

@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!");
}
}
}

public class MovieTicketApp {


public static void main(String[] args) {
Screen screen = new Screen("RRR", 182, 3, 250.0);

[Link]("Ravi");
[Link]("Anjali");
[Link]("Kiran");
[Link]("Priya"); // houseful

[Link]("Total bookings today: " + [Link]);


}
}

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

You might also like