0

Here is a very simple code:

  public class Test2 {

public static void main(String[] args)  {
        String a = "hello2"; 
        final String b = "hello";
        String d = "hello";
        String c = b + 2; 
        String e = d + 2;
        System.out.println((a));
        System.out.println((c));
        System.out.println((e));
        System.out.println((a == c));
        System.out.println((a == e));

    }
}

And the output is:

hello2
hello2
hello2
true
false

Please tell me why the last one is 'false'??Thanks

  • That is Java string pooling or String interning. – Syam S Sep 02 '15 at 09:14
  • It returns false, because these two variables point to two different objects. The more interesting question is why `a` and `c` point to the same object. Search here or on Google for "String literal pool" and "interned Strings". – Thilo Sep 02 '15 at 09:14
  • @Thilo - It is more about *compile-time constants* don't you think? – TheLostMind Sep 02 '15 at 09:17

3 Answers3

1
public static void main(String[] args)  {
        String a = "hello2"; 
        final String b = "hello"; // this will be a compile-time constant. `final String` makes a string compile-time-constant.
        String d = "hello";
        String c = b + 2; // The compiler will replace b+2 by "hello2"
        String e = d + 2; // d is not final. Hence value of b will be calculated at runtime.
        System.out.println((a));
        System.out.println((c));
        System.out.println((e));
        System.out.println((a == c));
        System.out.println((a == e));

    }
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
  • Thank you for answering. In your comment "d is not final. Hence value of b will be calculated at runtime.", do you mean e will be calculated at runtime? – xinaosun Sep 02 '15 at 17:00
0

This is because you're comparing objects, not the actual String value. Use .equals() to compare String value.

Amila
  • 5,195
  • 1
  • 27
  • 46
0

You should compare String values with equals() and not == operator. == compares the references and not the values.

Karthik R
  • 5,523
  • 2
  • 18
  • 30