This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
The moose likes Java in General and the fly likes Behavior of equal operator(==) in SOP Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

JavaRanch » Java Forums » Java » Java in General
Bookmark "Behavior of equal operator(==) in SOP" Watch "Behavior of equal operator(==) in SOP" New topic

Behavior of equal operator(==) in SOP

arfeen khan

Joined: May 13, 2011
Posts: 25
Hello Rancher's,

During my test program i found a weird behavior for equal operator .

The Problem is:
If i try to print the return value of "equal operator" for two reference variable pointing to same string object.
the result always comes FALSE.

Following is the code snippet--

Actual Result is:

inside if -- Got true for sr1==sr2
End of Program.

Expected Result:
inside if -- Got true for sr1==sr2
The value of sr1==sr2 [true].
End of Program.

The red marked line should come.

Can any Rancher, please suggest why this happening.

Kemal Sokolovic

Joined: Jun 19, 2010
Posts: 825

If you put:

you'll get the result you expected. The thing is you have to take care you understand operator precedence and associativity to get into more details. Simply put, what your line does:

is actually first concatenating "The value of sr1==sr2 [" and "Arfeen" and then compare it as "The value of sr1==sr2 [Arfeen" with other string because + operator is of higher precedence than == operator (it's also left associative). Hence, you only get the result of that comparison, which is false.

I hope I was clear, if you have any more doubts feel free to ask.

The quieter you are, the more you are able to hear.
Have you checked out Aspose?
subject: Behavior of equal operator(==) in SOP
jQuery in Action, 3rd edition