0

EDIT: I do not think this is a copy of an existing question. The references of my 2 declared string point at the same memory location, so why is my == (reference comparison) giving false? It is not a character by character comparison.

I am writing test files to get a better understanding of Java String references and comparisons. I expected the 3rd line of my code to be :

Should be true: true

Why is it not?

   public class testr {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String s = "s";
        String t = "s"; 

        System.out.println("String s hashcode: " + s.hashCode());
        System.out.println("String t hashcode: " + t.hashCode());
        System.out.println("Should be true: " + s==t);

    }

}

Output:

String s hashcode: 115
String t hashcode: 115
false
MarianD
  • 13,096
  • 12
  • 42
  • 54
VKkaps
  • 159
  • 3
  • 21
  • 2
    Doesn't make the output of `false` it pretty clear that your last print statement is evaluated as `("SHould be true: " + s)==t`, rather than `"SHould be true: " + (s==t)`? Thus, use explicit brackets. – Tom Feb 03 '18 at 03:22
  • @Tom ah - that was it. Thanks! – VKkaps Feb 03 '18 at 03:23

0 Answers0