• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

confusion with output

 
upanshu vaid
Ranch Hand
Posts: 83
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In this below code


output that is coming is
true
false
true

I am expecting the below output
true
true
true

any suggestion on this
Thanks and Regards.
 
Henry Wong
author
Marshal
Pie
Posts: 21496
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To start, do you know the difference between comparing via the equals() method versus comparing with the == operator?


And second, can you tell us why you expected the output that you expected?
 
K. Tsang
Bartender
Posts: 3521
16
Android Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah the classic == vs equals() method.

equals() method checks the content. == checks the reference position in the memory (stack or heap).

When you do "g1.substring(0,3)=="abc" ... whatever returned from the substring is NOT pointing to the same reference as g

 
upanshu vaid
Ranch Hand
Posts: 83
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


yes Henry I know the difference
the == operator is used to check the reference of the objects.
the equals method is used to check the contents of the objects.

I was expecting the expected output because in line 6 of code the substring returned by substring method will be equal to abc.
 
Rob Spoor
Sheriff
Pie
Posts: 20661
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Equal yes, but not a reference to the same object. The "abc" returned by the substring method is a new String object.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic