Search code examples
javastringpool

What will be the output from the following three code segments?


I'm currently on a self learning course for Java and have gotten completely stumped at one of the questions and was wonder if anyone can help me see sense...

Question: What will be the output from the following three code segments? Explain fully the differences.

public static void method2(){ 

    String mystring1 = "Hello World"; 

    String mystring2 = new String("Hello World"); 

    if (mystring1.equals(mystring2)) { 

        System.out.println("M2 The 2 strings are equal"); 

    } else { 

        System.out.println("M2 The 2 strings are not equal"); 

    } 

}

public static void method3(){ 

    String mystring1 = "Hello World"; 

    String mystring2 = "Hello World"; 

    if (mystring1 == mystring2) { 

        System.out.println("M3 The 2 strings are equal"); 

    } else { 

        System.out.println("M3 The 2 strings are not equal"); 

    } 

}

The answer I gave:

Method 2: "M2 The 2 strings are equal" It returns equal because even though they are two separate strings the (mystring1.equals(mystring2)) recognises that the two strings have the exact same value. If == was used here it return as not equal because they are two different objects.

Method 3: "M2 The 2 strings are equal" The 2 strings are equal because they are both pointing towards the exact same string in the pool. == was used here making it look at the two values and it recognises that they both have the exact same characters. It recognises that Hello World was already in the pool so it points myString2 towards that string.

I was pretty confident in my answer but it's wrong. Any help?


Solution

  • Both will return true.

    1) 2 new string objects are created but use .equals which means their actual value is compared. Which is equal.

    2) 1 new string object is created because they are both constant at compile time. This will result in them pointing to the same object.

    This sentence might be your issue:

    == was used here making it look at the two values and it recognises that they both have the exact same characters.

    == checks for reference equality whereas you're describing value equality.