Search code examples
javastringoperatorsequalityoperator-precedence

java println("a==b"+"is"+a==b) prints false instead of "a==b is true"


Possible Duplicates:
Getting strange output when printing result of a string comparison

Hi all,

System.out.println() behaving in a different way with strings. Can any one explain why

See the below code snippet

String a ="hello"
String b ="hello"

System.out.println("a==b"+"is"+a==b)

I expect this to print 'a==b is true', but it just prints false and I dont know why.


Solution

  • A single false is printed because you didn't group your boolean expression.

    The expression:

    "a==b"+"is"+a==b
    

    is evaluated as

    ("a==b"+"is"+a) == (b)
    

    while you wanted it to do a string concatenation:

    "a==b"+"is"+ (a==b)
    

    That said, you shouldn't compare strings using ==, as others pointed out.