Java MCQ

Previous Java Multiple Choice Questions Next

JAVA TRICKY strings MCQ

1

What will be the output of: String s1 = "Java"; String s2 = "Java"; System.out.println(s1 == s2);

Correct Answer: A) true

Both s1 and s2 point to the same string literal in the string pool, so == comparison returns true.

2

What will be the output of: String s1 = new String("Java"); String s2 = new String("Java"); System.out.println(s1 == s2);

Correct Answer: B) false

Using 'new' creates separate objects in heap memory, so == comparison returns false even though content is same.

3

What will be the output of: String s = "Java"; s.concat(" Programming"); System.out.println(s);

Correct Answer: B) Java

Strings are immutable in Java. The concat() method returns a new string but doesn't modify the original.

4

What will be the output of: String s1 = "Java"; String s2 = s1.substring(0); System.out.println(s1 == s2);

Correct Answer: A) true

When substring() returns the entire string, Java optimizes it to return the same string object from string pool.

5

What will be the output of: String s1 = "Java"; String s2 = "Ja" + "va"; System.out.println(s1 == s2);

Correct Answer: A) true

String concatenation of literals happens at compile time, so both refer to the same "Java" in string pool.

6

What will be the output of: String s1 = "Java"; String s2 = "Ja"; String s3 = s2 + "va"; System.out.println(s1 == s3);

Correct Answer: B) false

When concatenation involves a variable, it happens at runtime and creates a new String object in heap.

7

What will be the output of: String s = null; System.out.println(s + "Java");

Correct Answer: A) nullJava

The + operator converts null to "null" string and then concatenates with "Java".

8

What will be the output of: String s1 = "Java"; String s2 = s1.intern(); System.out.println(s1 == s2);

Correct Answer: A) true

intern() returns the canonical representation from string pool. Since s1 is already from pool, both are same.

9

What will be the output of: String s1 = new String("Java").intern(); String s2 = "Java"; System.out.println(s1 == s2);

Correct Answer: A) true

intern() moves the string to pool, so both s1 and s2 refer to the same object in string pool.

10

What will be the output of: String s = "Java"; s = s.toUpperCase(); System.out.println(s);

Correct Answer: B) JAVA

toUpperCase() returns a new string in uppercase. We're reassigning the reference to this new string.

Previous Java Multiple Choice Questions Next