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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With