Meaningless Drivel is fun!*
The moose likes Java in General and the fly likes confusion with output Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "confusion with output" Watch "confusion with output" New topic
Author

confusion with output

upanshu vaid
Ranch Hand

Joined: Sep 07, 2012
Posts: 73

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
Sheriff

Joined: Sep 28, 2004
Posts: 18847
    
  40

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?


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
K. Tsang
Bartender

Joined: Sep 13, 2007
Posts: 2419
    
    7

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


K. Tsang JavaRanch SCJP5 SCJD/OCM-JD OCPJP7 OCPWCD5
upanshu vaid
Ranch Hand

Joined: Sep 07, 2012
Posts: 73



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

Joined: Oct 27, 2005
Posts: 19696
    
  20

Equal yes, but not a reference to the same object. The "abc" returned by the substring method is a new String object.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
wood burning stoves
 
subject: confusion with output