2

When used String's intern method in program it gives some unexpected output i'm unable to understand why this gives such output

public class Test {

    public static void main(String[] args)
    {

        String str1 = "patty";
        String str2 = new String("patty");

        System.out.println("1   ->  "+ str1 == str2);

        String str3 = str2.intern();

        System.out.println("2   ->  "+ str1 == str3);
    }
}

in output it shows

false
false

but the expected output is

1   ->  false
2   ->  true

Can anyone please help me to understand this problem

vishal s.
  • 370
  • 1
  • 2
  • 21

1 Answers1

2

Even though str1 and str3 reference the same String instance, you are not comparing these references.

System.out.println("2   ->  "+ str1 == str3);

compares "2 -> "+ str1 to str3.

Try:

System.out.println("2   ->  "+ (str1 == str3));
Eran
  • 387,369
  • 54
  • 702
  • 768