Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange behavior of == in Java

I observed a strange behavior == operator in java. I am trying to print the out put as follows

String str1 = "Rajesh";
String str2 = "Rajesh";
System.out.println("Using equals() str1 and str2 Equals :"
            + str1.equals(str2));
System.out.println("Using == str1 and str2 Equals :" 
            + str1 == str2);

The first SOP statement printing

Using equals() str1 and str2 Equals :true

and the next SOP printing only false .

I tried compiling in both eclipse and Net Beans but result is the same . I am so confused why

Using == str1 and str2 Equals :

is not printing

Help me out in this

Thanks in advance,

Raj

like image 530
Raj Avatar asked Feb 09 '12 06:02

Raj


2 Answers

it's the same as ("Using == str1 and str2 Equals :" + str1) == str2 and this is false, of course. Expression is parsed from left to right and so at first it concatenates "Using == str1 and str2 Equals :" and str1, then applies == operator.

like image 125
shift66 Avatar answered Oct 20 '22 14:10

shift66


See http://bmanolov.free.fr/javaoperators.php for a table of operator precedence in Java.

The + operator is higher precedence than the == operator.

So, in effect, your code is equivalent to the following:

System.out.println( ("Using == str1 and str2 Equals :" + str1) == str2);

Note the placement of the parentheses that I added. It evaluates to this:

System.out.println( (str_x + str1) == str2);

And then to this:

System.out.println( str_y == str2 );

And then to this:

System.out.println( false );

In order to get the result you want, you must use parentheses to specify that you want the == operator to be resolved BEFORE the + operator:

System.out.println( "Using == str1 and str2 Equals :" + (str1 == str2));

Notice the new placement of the parentheses.

like image 28
Aaron Johnson Avatar answered Oct 20 '22 15:10

Aaron Johnson