Tricky And Unique Java Interview Questions

Tricky Java Code Examples Revealing Hidden Capabilities

Skilled Coder
4 min readAug 18, 2024

--

Whether you’re a seasoned programmer or a curious learner, these unique tricks examples will provide valuable insights into Java’s more subtle aspects and improve your coding prowess.

Here are some tricky Java situations where people often guess wrong, along with explanations.

Question 1 : String Pool and == Operator

What will be the output of the following Java code?

public class Main {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Ja" + "va";
System.out.println(s1 == s2);
}
}

Output: true

Explanation:

  • Both s1 and s2 refer to the same string literal "Java" in the string pool, so == compares their references, which are identical.

Question 2 : String Immutability and Concatenation

What will be the output of the following Java code?

public class Main {
public static void main(String[] args) {
String s1 = "Java";
String s2 = "Ja";
String s3 = s2 + "va";
System.out.println(s1 == s3);
}
}

--

--

Skilled Coder
Skilled Coder

Written by Skilled Coder

Sharing content and inspiration on programming.

No responses yet