Week 1 — Java Basics
Easy
1
EasySingle ChoiceWhich of the following correctly declares an integer variable in Java?
B is correct. In Java,
int is the primitive integer type (lowercase). integer, Int, and INTEGER are not valid Java primitive types. Integer (capital I) is the wrapper class, not a primitive type declaration.2
EasySingle ChoiceWhat is the output of the following statement?
System.out.println(10 / 3);
B is correct. Both operands are
int, so Java performs integer division — the decimal part is truncated. 10 ÷ 3 = 3 remainder 1, so the result is 3 (not 3.33). To get a decimal result, at least one operand must be a double: 10.0 / 3.3
EasySingle ChoiceWhich loop is guaranteed to execute its body at least once?
C is correct. The
do-while loop checks its condition after executing the body, so it always runs at least once. for and while check the condition before entering the body, so they may never execute if the condition is initially false.4
EasySingle ChoiceWhat does
Math.abs(-7) return?B is correct.
Math.abs(x) returns the absolute value — always non-negative. Math.abs(-7) returns 7. It works on int, long, float, and double types.5
EasySingle ChoiceWhich is the correct signature of the Java main method?
B is correct. The entry point must be
public static void main(String[] args). It must be public (JVM can access), static (called without an object), void (returns nothing), and accept a String[] parameter.Intermediate
6
IntermediateSingle ChoiceWhat is the output of the following?
System.out.println((int) 3.9);
B is correct. Explicit casting from
double to int truncates (drops the decimal part) — it does NOT round. So (int) 3.9 → 3, not 4. Contrast: Math.round(3.9) would give 4.7
IntermediateSingle ChoiceWhich operator has the HIGHEST precedence among these?
C is correct. Operator precedence (high → low):
! → * / % → + - → < <= > >= → == != → && → || → =. The unary logical NOT (!) has higher precedence than any arithmetic or comparison operator listed here.8
IntermediateSingle ChoiceWhat is printed?
int x = 5;
System.out.println(x++ + " " + ++x);
A is correct.
x++ (post-increment) uses x's current value 5 in the expression, then increments x to 6. Next, ++x (pre-increment) increments x from 6 to 7 first, then uses 7. Output: "5 7".9
IntermediateMulti-SelectWhich of the following are valid
Math class methods in Java?Select ALL that apply
A, B, C, E are correct.
Math.square() does NOT exist in Java — use Math.pow(x, 2) instead. Valid methods: pow, sqrt, abs, max, min, random, ceil, floor, round, log, sin, cos. All are static.10
IntermediateSingle ChoiceWhat is printed by this code?
for (int i = 0; i < 5; i++) {
if (i == 3) break;
System.out.print(i + " ");
}
A is correct. The loop prints 0, 1, 2 normally. When
i == 3, break immediately exits the loop before printing. So only 0 1 2 is printed.11
IntermediateSingle ChoiceWhich of the following CANNOT be used alone to distinguish two overloaded methods?
C is correct. Method overloading is determined by the method signature (name + parameter list). The return type is NOT part of the signature, so two methods with the same name and same parameters but different return types cause a compilation error — they cannot be distinguished by the compiler.
12
IntermediateMulti-SelectWhich of the following are primitive data types in Java?
Select ALL that apply
A, C, D, E are correct. Java has 8 primitives:
byte, short, int, long, float, double, boolean, char. String is a class (reference type). Integer is the wrapper class for int — also a reference type, not primitive.Hard
13
HardSingle ChoiceWhat is the output of this if-else chain?
int x = 10;
if (x > 5) {
System.out.print("A");
} else if (x > 8) {
System.out.print("B");
} else {
System.out.print("C");
}
A is correct. The first condition
x > 5 (10 > 5) is true, so "A" is printed and the entire if-else chain exits. The else if (x > 8) branch is never evaluated — in a chain, once a branch is taken, all others are skipped.14
HardMulti-SelectWhich statements about widening type conversion in Java are TRUE?
Select ALL that apply
A, C, E are correct. Widening goes from smaller → larger type (byte→short→int→long→float→double) and is automatic. B is wrong: widening generally preserves value (though
int/long → float/double can lose precision for very large integers, the concept is about no data loss in normal cases). D is wrong: double → float is narrowing (double is larger), not widening.15
HardSingle ChoiceWhat does this code print?
int result = 0;
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) continue;
result += i;
}
System.out.println(result);
A is correct.
continue skips even numbers. Only odd values are added: 1 + 3 + 5 = 9. Trace: i=1 (odd, add→1), i=2 (even, skip), i=3 (odd, add→4), i=4 (even, skip), i=5 (odd, add→9).16
HardSingle ChoiceGiven the method:
Which call is INVALID?
public static double compute(int a, double b)Which call is INVALID?
C is correct (invalid call). The first parameter requires an
int. Passing 3.0 (a double) would require narrowing conversion (double→int), which is not done implicitly. B is valid because 4 (int) is widened to double for the second parameter.17
HardMulti-SelectWhich statements about Java's
switch statement are TRUE?Select ALL that apply
A, B, E are correct. C is wrong:
switch supports byte, short, int, char, String, and enums — NOT float or double. D is wrong: default is optional. Fall-through (A) is a common pitfall — always add break unless intentional.18
HardSingle ChoiceWhat is the output?
int x = 15;
String r = (x % 2 == 0) ? "even" : (x % 3 == 0) ? "div3" : "other";
System.out.println(r);
B is correct. 15 % 2 = 1 (not 0) → not even. Then: 15 % 3 = 0 → "div3". Nested ternary evaluates left to right. Since 15 is odd but divisible by 3, result =
"div3".19
HardMulti-SelectWhich statements about method parameters and overloading in Java are TRUE?
Select ALL that apply
A, C, E are correct. B is wrong: primitive changes inside a method do NOT affect the caller (copy was passed). D is wrong: Java returns only one value; use arrays or objects for multiple values. C is correct but subtle: the reference itself is a copy — you can modify the object's fields but can't make the caller's variable point to a different object.
20
HardSingle ChoiceWhat does this recursive method print when called as
System.out.println(mystery(4))?public static int mystery(int n) {
if (n <= 1) return 1;
return n + mystery(n - 1);
}
B is correct. This computes the sum 1+2+...+n. Trace: mystery(4) = 4 + mystery(3) = 4 + 3 + mystery(2) = 4+3+2+mystery(1) = 4+3+2+1 = 10. Base case: mystery(1) = 1.
Week 2 — Arrays
Easy
1
EasySingle ChoiceWhat is the index of the last element in an array of size 10?
B is correct. Java arrays are 0-indexed. An array of size 10 has valid indices 0 through 9. Accessing index 10 throws
ArrayIndexOutOfBoundsException. Always use arr.length - 1 to get the last index safely.2
EasySingle ChoiceWhat is the default value of each element when you create
int[] arr = new int[5]?C is correct. Java initializes array elements to default values:
int/long/short/byte → 0, double/float → 0.0, boolean → false, char → '\u0000', object references → null. Unlike C/C++, Java never has garbage values.3
EasySingle ChoiceWhich correctly declares and creates an integer array of size 5?
B is correct. The preferred Java syntax places
[] after the type: int[] arr = new int[5];. While int arr[] = new int[5]; is also valid (C-style), options A (missing []), C (invalid keyword), and D (C-style without new) are wrong.4
EasySingle ChoiceHow do you get the number of elements in an array
arr?C is correct. Arrays have a
length field (not a method — no parentheses). arr.size() is for ArrayList, not arrays. arr.length() would cause a compilation error since length is not a method on arrays.5
EasySingle ChoiceWhat does the enhanced for-loop
for (int x : arr) do?B is correct. The enhanced for-loop provides each element value but no index. Modifying
x (a primitive copy) does NOT change the original array. Use a regular for loop when you need the index or want to modify elements.Intermediate
6
IntermediateSingle ChoiceWhat is the output?
int[] arr = {5, 3, 8, 1, 9};
System.out.println(arr[2]);
B is correct. Index 0→5, 1→3, 2→8, 3→1, 4→9. Arrays are 0-indexed, so
arr[2] is the third element: 8.7
IntermediateMulti-SelectWhich of the following create a true independent (deep) copy of a primitive array?
Select ALL that apply
B, C, D, E are correct. A (
int[] b = a) is only a reference copy — both variables point to the same array. Changing one changes the other. Options B, C, D, E all create a new, independent array with copied values.8
IntermediateSingle ChoiceWhat exception is thrown when you access
arr[-1] or arr[arr.length]?B is correct. Accessing any index outside [0, length-1] throws
ArrayIndexOutOfBoundsException at runtime. NullPointerException occurs when calling methods on a null array reference.9
IntermediateSingle ChoiceWhat does
Arrays.sort(arr) do to the array?B is correct.
Arrays.sort(arr) modifies the original array in-place, sorting in ascending order. It returns void. For descending order, you must sort then reverse, or use Arrays.sort(arr, Collections.reverseOrder()) with Integer arrays.10
IntermediateMulti-SelectWhich statements about 2D arrays in Java are TRUE?
Select ALL that apply
A, B, D, E are correct. C is false: Java supports ragged arrays where rows can have different lengths (declared as
int[][] rag = new int[3][];). This is because a 2D array is actually an array of array references.11
IntermediateSingle ChoiceWhat is printed?
int[][] m = {{1,2,3},{4,5,6}};
System.out.println(m.length + " " + m[0].length);
B is correct. The matrix has 2 rows (
m.length = 2) and 3 columns (m[0].length = 3). Output: "2 3".12
IntermediateSingle ChoiceIf you pass an array to a method and modify its elements inside the method, what happens to the original array?
B is correct. When an array is passed to a method, the reference (address) is copied. Both the caller's variable and the method's parameter point to the same array object. So modifying
arr[0] = 99 inside the method changes the original.Hard
13
HardSingle ChoiceWhat does
Arrays.binarySearch(arr, key) return when the key is NOT found?C is correct. When not found,
Arrays.binarySearch returns -(insertion point) - 1, where the insertion point is where the key would be inserted to keep the array sorted. This is always a negative number, letting you distinguish "not found" from index 0.14
HardMulti-SelectWhich are TRUE about
System.arraycopy(src, srcPos, dest, destPos, length)?Select ALL that apply
A, C, D, E are correct. B is false:
System.arraycopy copies INTO an existing dest array — it does NOT create a new array. You must pre-allocate dest. It copies primitive values by value, making them independent for primitive arrays.15
HardSingle ChoiceWhat is the output?
int[] a = {1, 2, 3};
int[] b = a;
b[0] = 99;
System.out.println(a[0]);
B is correct.
int[] b = a copies the reference, not the array. Both a and b point to the same array object in memory. So b[0] = 99 also changes a[0]. This is the classic "aliasing" problem.16
HardSingle ChoiceWhat is printed?
int[] arr = new int[5];
Arrays.fill(arr, 7);
System.out.println(Arrays.toString(arr));
B is correct.
Arrays.fill(arr, 7) sets every element to 7. Arrays.toString(arr) returns a formatted string like "[7, 7, 7, 7, 7]". Note: java.util.Arrays is automatically available with the import java.util.Arrays; statement (or java.util.*).17
HardMulti-SelectWhen would you choose binary search over linear search?
Select ALL that apply
A, B, D are correct. Binary search requires a sorted array (C is wrong). For tiny arrays (E), the overhead of sorting makes binary search impractical — linear search is fine for ≤10 elements. Binary search shines on large sorted datasets: 1 million elements → max 20 comparisons vs 1,000,000.
18
HardSingle ChoiceWhat is printed?
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6};
Arrays.sort(arr);
System.out.println(arr[0] + " " + arr[arr.length-1]);
B is correct. After sorting ascending:
{1, 1, 2, 3, 4, 5, 6, 9}. First element arr[0] = 1, last element arr[7] = 9. Output: "1 9".19
HardMulti-SelectWhich statements about Java arrays are TRUE?
Select ALL that apply
A, B, D, E are correct. C is false: a typed array (e.g.,
int[]) can only store that type. To mix types, you'd use an Object[] or a collection like ArrayList. Note: a == b on arrays compares references; use Arrays.equals(a, b) for content comparison.20
HardSingle ChoiceWhat is printed?
int[][] m = {{1,2},{3,4},{5,6}};
int sum = 0;
for (int[] row : m) {
sum += row[0];
}
System.out.println(sum);
B is correct. The loop accesses only column 0 of each row: row[0]=1, row[0]=3, row[0]=5. Sum = 1+3+5 = 9. The enhanced for-each treats each row as an
int[]. Week 3 — Sorting & Searching
Easy
1
EasySingle ChoiceWhat is the worst-case time complexity of linear search?
C is correct. Linear search checks each element one by one. In the worst case (element not found or at the end), it checks all n elements → O(n). Best case: O(1) (first element). Average: O(n/2) = O(n).
2
EasySingle ChoiceWhich algorithm requires the array to be sorted before it can be used?
D is correct. Binary search relies on the array being sorted to eliminate half the remaining elements at each step. It gives wrong results on unsorted arrays. Linear search, selection sort, and insertion sort work on any array.
3
EasySingle ChoiceIn each pass of selection sort (ascending), what is done?
B is correct. Selection sort scans the unsorted portion, finds the minimum, and swaps it with the first unsorted element. After each pass, the sorted portion grows by 1. This makes at most n swaps total.
4
EasySingle ChoiceWhat is the time complexity of binary search?
C is correct. Binary search halves the search space with each comparison → O(log₂ n). For 1 million elements: only ~20 comparisons. This is why it's drastically faster than linear search O(n) on large sorted datasets.
5
EasySingle ChoiceWhat does a typical linear search method return when the element is NOT found?
C is correct. By convention, a linear search that fails returns
-1 (since -1 is never a valid array index). This is the same convention as String.indexOf() which also returns -1 when not found.Intermediate
6
IntermediateSingle ChoiceIn insertion sort, what happens to the "current" element being processed?
B is correct. Insertion sort picks the current element, then scans backwards through the already-sorted portion, shifting elements right until it finds the correct insertion spot. Think of sorting playing cards in your hand.
7
IntermediateMulti-SelectWhich statements about selection sort are TRUE?
Select ALL that apply
A, B, D are correct. C is false: selection sort is NOT stable (swapping can change relative order of equal elements). E is false: insertion sort is O(n) on nearly-sorted arrays — far better than selection sort's always-O(n²). Selection sort's advantage is minimum swaps.
8
IntermediateSingle ChoiceAfter one complete pass of selection sort (ascending) on
{5, 2, 8, 3, 1}, what is arr[0]?C is correct. Pass 1: find minimum in {5,2,8,3,1} → min is 1 at index 4. Swap with index 0 (value 5). Array becomes
{1, 2, 8, 3, 5}. So arr[0] = 1.9
IntermediateSingle ChoiceWhat is the maximum number of comparisons binary search needs for an array of 1024 elements?
C is correct. Maximum comparisons = ⌊log₂(n)⌋ + 1 = ⌊log₂(1024)⌋ + 1 = 10 + 1 = 11. Each comparison halves the search space: 1024 → 512 → 256 → 128 → 64 → 32 → 16 → 8 → 4 → 2 → 1.
10
IntermediateMulti-SelectWhich statements about binary search are TRUE?
Select ALL that apply
A, B, D, E are correct. C is false — binary search gives undefined/wrong results on unsorted arrays. Always sort first with
Arrays.sort(arr) before calling Arrays.binarySearch().11
IntermediateSingle ChoiceTo swap
arr[i] and arr[j], which approach(es) work correctly?D is correct. A is wrong (overwrites arr[i] before saving it — data is lost). B (temp variable) is the standard, clearest approach. C (arithmetic trick) also works for integers but can overflow for large values. Both B and C are correct swap methods.
12
IntermediateSingle ChoiceWhat is the value of
args.length when running: java MyProgram hello world 42?B is correct.
args contains only the arguments AFTER the class name: args[0]="hello", args[1]="world", args[2]="42" → args.length = 3. The class name MyProgram is NOT included in args.Hard
13
HardMulti-SelectWhich correctly compare insertion sort vs selection sort?
Select ALL that apply
A, B, D, E are correct. C is false: both make O(n²) comparisons in the worst case; neither makes fewer than the other in general. Insertion sort's key advantage: O(n) for already-sorted data. Selection sort's key advantage: at most n swaps (useful when write operations are expensive).
14
HardSingle ChoiceAfter
Arrays.sort(arr) on {4, 2, 7, 1, 9}, what does Arrays.binarySearch(arr, 7) return?C is correct. After sorting:
{1, 2, 4, 7, 9} (indices 0-4). Value 7 is at index 3. Arrays.binarySearch returns the index where the key is found.15
HardSingle ChoiceWhat is the state of
{64, 25, 12, 22, 11} after ONE complete pass of selection sort (ascending)?A is correct. Pass 1: find min in entire array → min=11 at index 4. Swap with index 0 (value 64). Result:
{11, 25, 12, 22, 64}. Only ONE swap happens per pass in selection sort.16
HardMulti-SelectWhich are valid uses of command-line arguments in Java? (
public static void main(String[] args))Select ALL that apply
A, B, C, D are correct. E is wrong for two reasons: (1)
args.length is a field, not a method — no parentheses; (2) the program name is NOT in args at all, so you can't add 1 to get it. All arguments in args are Strings — use Integer.parseInt() or Double.parseDouble() to convert.17
HardSingle ChoiceWhat is the minimum number of comparisons binary search might need to find an element in a sorted array of 8 elements?
A is correct. Best case O(1): if the target is the middle element, it's found in 1 comparison. For an array of 8: middle index = 3 (or 4). If the key equals arr[3] on the first check — found in 1 comparison.
18
HardMulti-SelectIn which situations is linear search preferable over binary search?
Select ALL that apply
A, B, C are correct. D and E both favor binary search. For large sorted arrays, binary search is dramatically faster. Linear search is practical when: the data is unsorted, the dataset is tiny, or sorting overhead/constraints prevent pre-sorting.
19
HardSingle ChoiceInsertion sort processes
{3, 1, 4, 1, 5}. In the third pass (inserting index 2, value = 4), what happens to element 4?B is correct. After passes 1&2: sorted portion =
{1, 3}, remaining = {4, 1, 5}. Current element = 4. Compare 4 with 3: 4 > 3, so no shifting needed. 4 stays at index 2. Array = {1, 3, 4, 1, 5}.20
HardMulti-SelectWhich are TRUE about the
java.util.Arrays class?Select ALL that apply
A, C, D, E are correct. B is false:
Arrays.sort() returns void and sorts in-place. Common mistake: printing the return value of Arrays.sort() — it returns nothing.Week 4 OOP — Classes, Objects & Encapsulation
0 / 20
1
EasySingle ChoiceWhich keyword is used to create a new object in Java?
C is correct. The
new keyword allocates memory and calls the constructor: Dog d = new Dog();2
EasySingle ChoiceWhich access modifier makes a field inaccessible from outside the class?
B is correct.
private fields are only accessible within the class they are declared in — the core idea behind encapsulation.3
EasySingle ChoiceFollowing Java naming conventions, what should a getter for a field called
age be named?A is correct. Java convention: getters are named
get + FieldName (capitalized). For boolean fields, use is prefix instead.4
EasySingle ChoiceA constructor must have the same name as ___.
B is correct. A constructor's name must exactly match the class name and it has no return type — not even
void.5
EasySingle ChoiceA
static field in a class belongs to ___.C is correct. Static fields are class-level — all instances share the same copy. Common use:
static int count = 0; to track how many objects were created.6
IntermediateMulti SelectWhich of the following are true about constructors? (Select all that apply)
A, B, D are correct. C is false — constructors cannot be static. E is false — fields get default values if not set (0, null, false).
7
IntermediateSingle ChoiceInside an instance method, what does the
this keyword refer to?B is correct.
this is a reference to the current instance. It's commonly used to disambiguate between a parameter and a field: this.name = name;8
IntermediateSingle ChoiceWhat is encapsulation?
C is correct. Encapsulation bundles data (fields) and behavior (methods) together, exposing only what is necessary. It protects the internal state from invalid changes.
9
IntermediateSingle ChoiceGiven:
How can code outside the class read the value of
class Car { private int speed; }How can code outside the class read the value of
speed?B is correct. The standard encapsulation pattern: make fields
private, provide a public getter. This lets the class control how data is exposed.10
IntermediateMulti SelectWhich of the following are true about
static methods? (Select all that apply)A, C, D are correct. B is false — static methods have no
this, so they can't access instance fields directly. E is false — static methods can have any return type.11
IntermediateSingle ChoiceWhat is the default value of an uninitialized
int instance field?A is correct. Instance fields get default values automatically:
int/long/short/byte → 0, double/float → 0.0, boolean → false, objects → null.12
IntermediateMulti SelectWhich statements about
private access are correct? (Select all that apply)B, C, E are correct. A is false —
private restricts access to the declaring class only, not even same-package classes. D is false — protected allows subclass and same-package access.13
HardSingle ChoiceYou define:
Then call:
class Box { Box(int size) { } }Then call:
Box b = new Box(); What happens?C is correct. Java only provides a free no-arg constructor when you write no constructor at all. Once you define any constructor, the default is gone. Fix: add
Box() { } explicitly.14
HardSingle ChoiceWhat is the output of the following code?
String s = null; System.out.println(s.length());
B is correct.
s holds null — no object. Calling any method on null throws NullPointerException at runtime. Always check for null before calling methods on object references.15
HardMulti SelectWhich statements correctly distinguish instance variables from static variables? (Select all that apply)
A, C, D are correct. B is false — static variables live as long as the class is loaded, not tied to any object's lifecycle. E is false — instance variables require an object reference to access.
16
HardSingle ChoiceConsider this class. What does calling
new Counter() then new Counter() produce for Counter.count?
class Counter {
static int count = 0;
Counter() { count++; }
}D is correct.
count is static, shared by all objects. Each constructor call increments the same counter. After two new Counter() calls, Counter.count == 2. This is a classic pattern to count how many instances were created.17
HardSingle ChoiceWhat does
this(10) do when placed as the first line of a constructor?A is correct.
this(...) is constructor chaining — it delegates to another constructor in the same class. It must be the very first statement. super(...) is used to call the parent constructor.18
HardMulti SelectWhich of the following are genuine benefits of encapsulation? (Select all that apply)
A, B, D are correct. Setters let you add validation logic. Internal refactoring doesn't break callers since they only see the public API. C is false — encapsulation is about safety, not performance. E is false — constructors are still essential.
19
HardSingle ChoiceWhat is the output of the following code?
class Dog {
String name;
Dog(String name) { this.name = name; }
void bark() { System.out.println(name + " says woof"); }
}
// In main:
Dog d1 = new Dog("Rex");
Dog d2 = d1;
d2.name = "Max";
d1.bark();B is correct.
d2 = d1 copies the reference, not the object. Both d1 and d2 point to the same object in memory. Changing d2.name also changes what d1.name sees — they are aliases.20
HardMulti SelectWhich of the following correctly describe the relationship between a class and an object? (Select all that apply)
B, C, E are correct. A is reversed — the class is the blueprint, the object is the instance. D is false — objects store field values, not source code. Think of a class as a cookie cutter and objects as the cookies.
Week 5 Thinking in Objects — Strings, Wrappers & Composition
0 / 20
1
EasySingle ChoiceIn Java,
String objects are ___.B is correct.
String is immutable. Methods like toUpperCase() return a new String — they don't modify the original. This is why Strings are safe to share.2
EasySingle ChoiceWhich method should you use to compare the content of two
String objects?C is correct.
== compares references (memory addresses). equals() compares actual character content. compareTo() returns an ordering, not equality.3
EasySingle ChoiceWhat is autoboxing in Java?
A is correct. Autoboxing:
Integer i = 42; — Java wraps 42 into an Integer object automatically. Unboxing is the reverse: int n = i;4
EasySingle ChoiceWhich method converts the
String "42" to the int value 42?B is correct.
Integer.parseInt(String) parses a numeric string into an int. If the string isn't a valid integer, it throws NumberFormatException.5
EasySingle ChoiceWhat does
"Hello".length() return?C is correct.
"Hello" has 5 characters, so length() returns 5. Note: for arrays, length is a field (no parentheses); for Strings and ArrayLists, length()/size() are methods.6
IntermediateSingle ChoiceWhat is the output of this code?
String a = "hello";
String b = "hello";
String c = new String("hello");
System.out.println(a == b);
System.out.println(a == c);B is correct. String literals
a and b point to the same interned object in the String pool → true. new String(...) forces a new heap object → a == c is false. Always use .equals() to compare content.7
IntermediateMulti SelectWhich of the following are valid
String methods in Java? (Select all that apply)B, C, D are correct. A is false —
append() belongs to StringBuilder, not String. E is false — push() is a Stack method, not String. String's main methods: length(), charAt(), substring(), indexOf(), toUpperCase(), toLowerCase(), trim(), startsWith(), endsWith(), contains().8
IntermediateSingle ChoiceWhat is the difference between composition and aggregation?
C is correct. Composition (strong ownership): a
Room inside a House — destroy the house, rooms are gone. Aggregation (weak ownership): a Student in a Course — delete the course, the student still exists.9
IntermediateSingle ChoiceWhat does
"Hello World".substring(6) return?A is correct.
substring(6) returns all characters from index 6 to end. Indices: H=0, e=1, l=2, l=3, o=4, (space)=5, W=6. So index 6 is 'W' → "World".10
IntermediateMulti SelectWhich are true about wrapper classes like
Integer, Double, Boolean? (Select all that apply)A, C, D are correct. B is false — wrapper classes are immutable, just like String. E is false — primitives are faster; wrappers add object overhead. Wrapper classes:
int→Integer, double→Double, char→Character, boolean→Boolean, etc.11
IntermediateSingle ChoiceAn immutable class should have ___. (Choose the best description)
B is correct. Rules for an immutable class: (1) declare fields
private final, (2) initialize via constructor, (3) provide no setter methods, (4) make the class final to prevent subclassing that breaks immutability.12
IntermediateMulti SelectA
Library class has a field List<Book> books. Which of the following correctly describe this as a composition relationship? (Select all that apply)A, B, E are correct. In composition, the child's lifecycle is tied to the parent. C and D describe aggregation, where the child can outlive or be shared beyond the parent.
13
HardSingle ChoiceWhat is the output of this code?
String s = "Java";
s.concat(" Programming");
System.out.println(s);C is correct. Strings are immutable.
concat() returns a new String but the result is discarded. s still points to "Java". Fix: s = s.concat(" Programming");14
HardSingle ChoiceWhat does this print?
Integer x = 127; Integer y = 127; Integer a = 128; Integer b = 128; System.out.println(x == y); System.out.println(a == b);
B is correct. Java caches
Integer objects in the range −128 to 127. So x and y share the same cached object → true. For 128 and above, new objects are created → a == b is false. Always use .equals() with wrapper types.15
HardMulti SelectWhich of the following are true about Java garbage collection? (Select all that apply)
B, C, E are correct. A is false — Java has no
delete. D is false — setting to null makes the object eligible for GC, but memory isn't freed instantly; the GC decides when to reclaim it.16
HardSingle ChoiceWhat does this print?
String s = " Hello "; System.out.println(s.trim().toLowerCase().charAt(1));
D is correct. Step by step: (1)
trim() → "Hello", (2) toLowerCase() → "hello", (3) charAt(1) → index 1 = 'e'. Method chaining works because each String method returns a new String.17
HardMulti SelectWhich of the following correctly describe how
StringBuilder differs from String? (Select all that apply)A, C, D are correct. B is false —
StringBuilder is mutable, so its hashCode can change, making it unreliable as a map key. E is false — immutability is a String trait, not StringBuilder.18
HardSingle ChoiceA
Person class contains an Address object as a field. The Address can be shared across multiple Person objects. This is an example of ___.C is correct. When the contained object can be shared and survives the container, it's aggregation (weak "has-a"). If Person created and exclusively owns the Address, that would be composition (strong "has-a").
19
HardMulti SelectWhich of the following produce a
NumberFormatException at runtime? (Select all that apply)A, B, D are correct.
parseInt requires a whole number string. "12.5" has a decimal point, "" is empty, "abc" is not a number — all throw NumberFormatException. C and E are valid: "99" is a valid int, "3.14" is a valid double.20
HardMulti SelectWhich of the following are properties of a well-designed immutable class? (Select all that apply)
B, D, E are correct. A is wrong — fields must be
private to prevent external mutation. C directly breaks immutability — setters are forbidden. A truly immutable class: final class, private final fields, constructor-only initialization, no setters.