0

This code prints "B". Shouldn't it print nothing? I have read that concatenation (+) is like executing a method and therefore it results with new String but here it is not the case. I thought that maybe that's because def variable is final but compound operator with def variable does not work the same way...

String abcdef = "abcdef";
final String def = "def";
String a = "abc";
a += def;
String b = "abc" + def;
String c = "abc";
c = c + def;
if(abcdef == a) {
    System.out.println("A");
}
if(abcdef == b) {
    System.out.println("B");
}
if(abcdef == c) {
    System.out.println("C");
}
bridgemnc
  • 189
  • 1
  • 2
  • 11
  • 2
    Don't use "==" to compare objects. "==" will only match if the object has the same memory. In many cases a string will be added to a "literal pool" so it in fact does become the same object. Use the `equals(...)` method. In this case the "==" happens to work because the string is interned. – camickr Oct 17 '20 at 15:10

3 Answers3

1

I presume you realize you're supposed to compare Strings with equals and not ==. However, look at the identity hashCodes for the strings. abcdef and b have the same one. That is why they are equal using == They are referencing the same object from the internal cache.

String abcdef = "abcdef";
final String def = "def";
String a = "abc";
a += def;
String b = "abc" + def;
String c = "abc";
c = c + def;
System.out.println("a = " + System.identityHashCode(a)
        + " abcdef = " + System.identityHashCode(abcdef));
System.out.println("b = " + System.identityHashCode(b)
+ " abcdef = " + System.identityHashCode(abcdef));
System.out.println("c = " + System.identityHashCode(c)
+ " abcdef = " + System.identityHashCode(abcdef));
if (abcdef == a) {
    System.out.println("A");
}
if (abcdef == b) {
    System.out.println("B");
}
if (abcdef == c) {
    System.out.println("C");
}

Prints

a = 925858445 abcdef = 798154996
b = 798154996 abcdef = 798154996
c = 681842940 abcdef = 798154996
B
WJS
  • 36,363
  • 4
  • 24
  • 39
0

In Java the operator "==" checks if the two operands reference to the same object. Do not use "==" with any objects including Strings. And note Java Strings are immutable. That mean all the operations with them don't modify them but create new objects.

-2

This is happening because b is equal to "abc" + def, and def is equal to "def". So, essentially, you are comparing "abcdef" with "abcdef" by using abcdef == b.

So, in conclusion, it will not print nothing, because "abcdef" == "abcdef" always evaluates to true.

shreyasm-dev
  • 2,711
  • 5
  • 16
  • 34
  • But a and c are also "abcdef" and corresponding if's do not print "A" and "C". Only "B" is printed. – bridgemnc Oct 17 '20 at 15:09
  • Yes comparing two literal strings will always evaluate to true. But it is not true the two variables containing the string will evaluate to true. It depends if the string has been added to the literal pool or has been interned. – camickr Oct 17 '20 at 15:15