• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why does it do this???  RSS feed

 
James Hambrick
Ranch Hand
Posts: 282
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


When I run it the ouput is True and then Flase, but shouldn't it hit the .equals first and output Equals and False? If I comment out the if statement that displays True then equals is displayed. I thought it used the fist valid statement.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Each of your "if" statements is independent of the others. They're three separate statements so each one of the conditions is evaluated and every one that applies is executed. For the first class, the string is first set to "Equals" because the first condition is true, but the method keeps on executing and the string is then set to "True" because that condition is true also.

I think you're thinking of how "if... else" behaves. The "else" keyword connects multiple if statements together so that only the first matching condition executes its statement:



Note that the last condition (if (a != b)) could be removed, and you'd just use the "else", since if the second condition isn't true the third one must be, making the last condition redundant.
 
Jagan Nambi
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
James,

Ernest is perfectly right in his explanation. Just to elaborate further, Ernest mentioned that your second condition "if (a == b)" will also return True. If you are wondering why, then it's because in Java two strings that have the same "value" WILL point to the SAME object in memory (on the heap). So, in your code, in the first check, "a" and "b" have the same value and point to the same object. Hence a == b.

Hope this helps.

Ciao,
Jagan.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two literal Strings will refer to the same object -- two Strings that both appear as double-quoted text within the program. Strings created some other way -- for example, read as user input -- won't behave this way.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!