Challenge - 5 Problems
Reference Types Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Java code with String references?
Consider the following Java code snippet. What will be printed when it runs?
Java
public class Main { public static void main(String[] args) { String a = "hello"; String b = a; a = "world"; System.out.println(b); } }
Attempts:
2 left
💡 Hint
Remember that Strings are immutable and variables hold references.
✗ Incorrect
Variable 'b' holds the reference to the original string "hello". Changing 'a' to "world" does not affect 'b'. So printing 'b' outputs "hello".
❓ Predict Output
intermediate2:00remaining
What is the output of this Java code with arrays and references?
Look at this Java code. What will it print?
Java
public class Main { public static void main(String[] args) { int[] arr1 = {1, 2, 3}; int[] arr2 = arr1; arr2[0] = 10; System.out.println(arr1[0]); } }
Attempts:
2 left
💡 Hint
Arrays are objects and variables hold references to them.
✗ Incorrect
Both 'arr1' and 'arr2' refer to the same array object. Changing arr2[0] changes arr1[0]. So output is 10.
🔧 Debug
advanced2:00remaining
What error does this Java code produce?
Examine this Java code. What error will it cause when compiled or run?
Java
public class Main { public static void main(String[] args) { String s = null; if (s.equals("test")) { System.out.println("Match"); } } }
Attempts:
2 left
💡 Hint
Calling a method on a null reference causes an error.
✗ Incorrect
Calling s.equals(...) when s is null causes a NullPointerException at runtime.
🧠 Conceptual
advanced2:00remaining
How many objects are created in this Java code?
Consider this Java code snippet. How many distinct objects are created in memory?
Java
public class Main { public static void main(String[] args) { String s1 = new String("abc"); String s2 = "abc"; String s3 = s1; } }
Attempts:
2 left
💡 Hint
Remember string literals and new String() create objects differently.
✗ Incorrect
The literal "abc" creates one object in the string pool. new String("abc") creates a new distinct object. s3 just references s1, no new object.
❓ Predict Output
expert2:00remaining
What is the output of this Java code with object references and mutation?
Analyze this Java code. What will it print?
Java
class Box { int value; Box(int v) { value = v; } } public class Main { public static void main(String[] args) { Box b1 = new Box(5); Box b2 = b1; b2.value = 10; b1 = new Box(20); System.out.println(b2.value); } }
Attempts:
2 left
💡 Hint
Changing b1 to a new object does not affect b2's reference.
✗ Incorrect
b2 and b1 initially point to the same Box object. Changing b2.value to 10 affects that object. Then b1 points to a new Box(20), but b2 still points to the old object with value 10.