0
class test {

public static void main(String[] args) {
    String a = "Hiabc";
    String b = "abc";
    String c = "abc";
    System.out.println(a.substring(2,5)==b);
    System.out.println(b==c);
}
}

output:
false
true

As far as I understand, Java's == look for addresses of the two compared objects. Yet, I don't understand why b==c is true because they must have different addresses. Also, if b==c, then why is a.substring(2,5), which is "abc" == b false?

foothill
  • 483
  • 3
  • 8
  • 18

2 Answers2

1

As far as I understand, Java's == look for addresses of the two compared objects.

Almost correct. Java uses references not addresses, e.g. a reference is strongly typed: See https://softwareengineering.stackexchange.com/questions/141834/how-is-a-java-reference-different-from-a-c-pointer

why b==c is true

The variable b and c are initialized with the same string reference, because they reference the same string literal "abc".

why doesn't substring expression reference the string literal "abc"?

Because the javadoc of substring() says

Returns a new string that is a substring of this string.

So the method does not ensure that a reference to a string from the constant pool is returned. If you want this you have to do

a.substring(2,5).intern()

and than

a.substring(2,5).intern()==b

will be true.

Community
  • 1
  • 1
René Link
  • 48,224
  • 13
  • 108
  • 140
0

Never compare strings with == in Java. Use .equal or .equalIgnoreCase methods instead.

The difference between a.substring(2,5) and b is because substring created another String object and it's on a different location than b. It's not about the characters ...

daxur
  • 359
  • 1
  • 11