Java MCQ
JAVA TRICKY strings MCQ
What will be the output of: String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2);
Both s1 and s2 point to the same string literal in the string pool, so == comparison returns true.
What will be the output of: String s1 = new String("Java"); String s2 = new String("Java"); System.out.println(s1 == s2);
Using 'new' creates separate objects in heap memory, so == comparison returns false even though content is same.
What will be the output of: String s = "Java"; s.concat(" Programming"); System.out.println(s);
Strings are immutable in Java. The concat() method returns a new string but doesn't modify the original.
What will be the output of: String s1 = "Java"; String s2 = s1.substring(0); System.out.println(s1 == s2);
When substring() returns the entire string, Java optimizes it to return the same string object from string pool.
What will be the output of: String s1 = "Java"; String s2 = "Ja" + "va"; System.out.println(s1 == s2);
String concatenation of literals happens at compile time, so both refer to the same "Java" in string pool.
What will be the output of: String s1 = "Java"; String s2 = "Ja"; String s3 = s2 + "va"; System.out.println(s1 == s3);
When concatenation involves a variable, it happens at runtime and creates a new String object in heap.
What will be the output of: String s = null; System.out.println(s + "Java");
The + operator converts null to "null" string and then concatenates with "Java".
What will be the output of: String s1 = "Java"; String s2 = s1.intern(); System.out.println(s1 == s2);
intern() returns the canonical representation from string pool. Since s1 is already from pool, both are same.
What will be the output of: String s1 = new String("Java").intern(); String s2 = "Java"; System.out.println(s1 == s2);
intern() moves the string to pool, so both s1 and s2 refer to the same object in string pool.
What will be the output of: String s = "Java"; s = s.toUpperCase(); System.out.println(s);
toUpperCase() returns a new string in uppercase. We're reassigning the reference to this new string.