0

I have come across this question in a test:

class Hello {
    public static void main(String[] args){
        String hello = "Hello", lo = "lo";
        System.out.println(hello == ("Hel" + "lo"));
        System.out.println(hello == ("Hel" + lo));
        System.out.println(hello == ("Hel" + lo).intern());
    }
}

The output is:

true
false
true

Why is the second output false?

Tom
  • 16,842
  • 17
  • 45
  • 54
Sempliciotto
  • 107
  • 1
  • 2
  • 6
  • 3
    possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – antonio Mar 11 '15 at 12:02

4 Answers4

5

It prints 'false' because the concatenation of the String constant "Hel" and the String object 'lo' results in a seaparate, anonymous string object, with its own unique object reference. Thus, the "hello" String object and the concatenated string are different objects based on object reference (== operator, not by String value with String.equals()).

Oscar
  • 81
  • 5
2

== compares the references of two sides.

Here, for hello == ("Hel"+lo), the references of two sides are not the same. So, it returns false.

For comparing values, use equals() method.

Minar Mahmud
  • 2,577
  • 6
  • 20
  • 32
  • hello == ("Hel"+"lo") returns true "concatenation of String literals happens at compile time and results in same object." See link from @antonio's comment to the question – RahulArackal Mar 11 '15 at 13:01
1

I think it is because in the second output ("Hel" + lo) is no more in the string. The equality "==" operator compares object memory location and not characters of String.By default Java puts all string literal into string pool, but you can also put any string into pool by calling intern() method of java.lang.String class, like string created using new() operator.

flyingmachine
  • 107
  • 1
  • 6
1

I think it Comparision Literal Problem.

It Works.

System.out.print((hello.equals("Hel"+lo)) + " "); 
System.out.print((hello == ("Hel"+"lo")) + " "); 
Aravinthan K
  • 1,763
  • 2
  • 19
  • 22