Java String Interview Questions - 1

What is the output of following Java code:


public class TestString {

 public static void main(String[] args) {

     String str1 = "Hello";

     String str2 = new String("Hello");

     System.out.print(str2 == "Hello");

 }

}

Explanation:




Line 1: String str1 = "Hello";

Here String literal (object) is created in the String constant pool area of the heap memory. JVM see that it is string literal and there is no existing literal with that value in String constant pool, so it creates a new String literal with value "Hello" in the String constant pool. This is done by JVM for efficient usage of memory. The reference variable str1 refers(read have address of this String literal) to this String literal. 


Line 2: String str2 = new String("Hello");

Here as we are creating String object using new operator, JVM creates a new String object in heap with value "Hello". str2 refers to(or read have address of this newly created object in heap) to object in heap.


Line 3:  System.out.print(str2 == "Hello");

When we compare two object references using '==' , we are comparing whether two object references are pointing to same object in memory or not. If two object references are pointing to same object in memory or in other words if two object references have addresses of same object in memory, then result of comparing two object references using '==' will return true and if two object references have address of two different memory locations then comparison will return false.


so str1 == str2 would have returned false as str1 has address of String object in String constant pool and str2 has memory address of String object in heap and of course as two addresses are different, result of comparison will be false.

As in our case, we are comparing str2 (which is reference to String object in heap) with String literal "Hello" using '==', it is apparently comparing memory address of the String in heap(4444) with memory address of the String  literal "Hello" in String constant pool(5555), which is of course not equal, so answer will be false.