File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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

substring, strings, and =='s

Eric Lam

Joined: Oct 26, 2004
Posts: 2
if(asdf.substring(0,1) == "e") {

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

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.


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).

Eric Lam

Joined: Oct 26, 2004
Posts: 2
Great, thanks, learned something new.
I agree. Here's the link:
subject: substring, strings, and =='s
It's not a secret anymore!