Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

substring, strings, and =='s

 
Eric Lam
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Great, thanks, learned something new.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic