0

I know that, in Java, two strings should typically be compared using a .equals() method, and that using == only compares memory locations. However, I wrote up this test code real quick in Eclipse and it's returning true and no one that I'm working with can figure out why. Did Java update to support direct comparisons of strings and just no one realized or are we crazy? Stack Overflow won't let me post a picture of the console but it prints out true.

Here's the code:

    public class Thing {
        public static void main(String[] args){
            String ar = "fish";
            String ar2 = "fish";
            System.out.println(ar == ar2);
        }
    }

2 Answers2

0

Cameron: because here they both refer to the same address in the memory. that doesn't mean it will always happen when you compare two Strings with the same value like this.

Stultuske
  • 9,296
  • 1
  • 25
  • 37
-3

Strings are stored on the String pool, when you declare a new String with the same value it will reference the existing one. That is the reason why it is returning true.

Vasco Lameiras
  • 344
  • 3
  • 15
  • 2
    Wrong. very wrong. just try to run the above code, but add: String tester = new String("fish"); System.out.println(ar == tester); And you will see your error. – Stultuske Apr 30 '15 at 13:53
  • "*Strings are stored on the String pool*" is only partially true. You need to be more precise, which strings (because not all of them are) and preferably how they are placed there. – Pshemo Apr 30 '15 at 13:55
  • Thanks for the feedback, I wasn't aware of the difference. Just got a nice explanation at http://stackoverflow.com/questions/2486191/java-string-pool – Vasco Lameiras Apr 30 '15 at 14:00