wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes substring, strings, and =='s Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "substring, strings, and == Watch "substring, strings, and == New topic
Author

substring, strings, and =='s

Eric Lam
Greenhorn

Joined: Oct 26, 2004
Posts: 2
if(asdf.substring(0,1) == "e") {
System.out.println("thingworks");
}

Okay, I'm pulling my hair out. Assuming String asdf = "eric", therefore asdf.substring(0,1) = "e", why the fudge won't it proceed?

Thanks.
Dun Dagda
Ranch Hand

Joined: Oct 12, 2004
Posts: 54
You probably need to use something like:


i.e. use the equals() method of string, rather than ==, since the latter only compares the memory location of the two objects (which will always be false in this case) rather than compare their content, which is what you want.

DD


SCJP 1.4<br />SCWCD (in progress)
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
Or to try and put it in a C++ perspective
what you typed is:


what you want is:


In the first instance you compare pointers which are obviously different.
In the second you compare the content of the pointers which is identical (a letter e).
In Java that's done through equals() more or less as you compare the content of objects (so not just the content of data referred to by a pointer location as in the second example).


42
Eric Lam
Greenhorn

Joined: Oct 26, 2004
Posts: 2
Great, thanks, learned something new.
 
GeeCON Prague 2014
 
subject: substring, strings, and =='s