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

Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
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
Similar Threads
Random Number from Math
AWK tutorial how to delimiter a file
i finish building the fuction but in certain cases..
Regular Expression for any number
Regular Expression issue