Challenge - 5 Problems
String Comparison Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of String equality check with == operator
What is the output of this Java code snippet?
Java
public class Main { public static void main(String[] args) { String a = "hello"; String b = "hello"; System.out.println(a == b); } }
Attempts:
2 left
💡 Hint
Remember that string literals are interned in Java.
✗ Incorrect
In Java, string literals with the same content point to the same object in the string pool, so 'a == b' is true.
❓ Predict Output
intermediateOutput of String equality check with new operator
What is the output of this Java code snippet?
Java
public class Main { public static void main(String[] args) { String a = new String("hello"); String b = new String("hello"); System.out.println(a == b); } }
Attempts:
2 left
💡 Hint
The 'new' keyword creates new objects in memory.
✗ Incorrect
Using 'new' creates distinct String objects, so 'a == b' compares references and returns false.
❓ Predict Output
advancedOutput of equals() method for String comparison
What is the output of this Java code snippet?
Java
public class Main { public static void main(String[] args) { String a = new String("hello"); String b = "hello"; System.out.println(a.equals(b)); } }
Attempts:
2 left
💡 Hint
The equals() method compares string content, not references.
✗ Incorrect
The equals() method returns true if the content of the strings is the same, regardless of object references.
❓ Predict Output
advancedOutput of compareTo() method for String comparison
What is the output of this Java code snippet?
Java
public class Main { public static void main(String[] args) { String a = "apple"; String b = "banana"; System.out.println(a.compareTo(b)); } }
Attempts:
2 left
💡 Hint
compareTo returns a negative number if the first string is lexicographically less than the second.
✗ Incorrect
Since 'apple' comes before 'banana' lexicographically, compareTo returns a negative integer.
❓ Predict Output
expertOutput of String interning and == operator
What is the output of this Java code snippet?
Java
public class Main { public static void main(String[] args) { String a = new String("test"); String b = a.intern(); String c = "test"; System.out.println(a == b); System.out.println(b == c); } }
Attempts:
2 left
💡 Hint
intern() returns the string from the pool, which may differ from the original object.
✗ Incorrect
'a == b' is false because 'a' is a new object, 'b' is the interned string. 'b == c' is true because both refer to the same interned string.
