• Post Reply Bookmark Topic Watch Topic
  • New Topic

==operator  RSS feed

 
sampada shukla
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a confusion in below statements:


why the output is false true.when in both string and Integer comparison we are comparing object reference to the value?



 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sampada shukla wrote:I have a confusion in below statements:

Hi sampada, and welcome to JavaRanch.

First: When you post code, please be sure to put it in code tags. I've done it for you this time - see how much better it looks?

why the output is false true.when in both string and Integer comparison we are comparing object reference to the value?

Because clearly the compiler thinks that in the second case, the two objects you're comparing are the same.

Which makes me think that you have not copied your code correctly, because there's no way that 2nd comparison should be true based on what I see.

Winston

PS: You will help yourself (and us) no end if you indent your code properly.
 
Nigel Browne
Ranch Hand
Posts: 704
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sampada shukla wrote:

why the output is false true.when in both string and Integer comparison we are comparing object reference to the value?



It isn't the output is false.
The first if statement makes the comparison between the String literal "Hello" and the Sting Object t, which are not the same.
The second if statement compares an Integer object with an int primative, which are not the same and due to being false doesn't print anything.
If you wish to assert that the value of String object t equals hello use the following
 
Campbell Ritchie
Marshal
Posts: 56525
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
sampada shukla wrote:. . . . . .
you should avoid if elses like that. You can usually use the ?: operator as you will see in the old Sun style guide §10.5.2. It is simpler to write this:
System.out.println("hello" == t);
There is no need to write the operands of the == that way round; there is no risk of finding null by mistake in that situation. You can write
t == "hello"
 
Fred Kleinschmidt
Bartender
Posts: 571
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is not clear what results you expected to get. Specifically, what do you (Sampada) expect from


If you expect it to be true, you need to learn more about how to compare strings.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!