Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

problem with string comparison

  Asked By: Anpu    Date: Apr 19    Category: Java    Views: 627
  

here is a segment of code I can't get to work. I've run this through the project
builder debugger on mac os x and it doesn't go into the if and print "help"
when 's' and 'contentFlag" are equal. If I change it to 'if(s != contentFlag)"
it
goes into the if statement everytime as it should. I think there is something
with strings that i'm missing. Can someone help me out?

String contentFlag = "<-- :?: -->";
while ((s = templateFile.readLine()) != null)
{
s = s.trim();
if(s == contentFlag)
System.out.println("help");
// {
// System.out.println("<TD>");
// while ((s2 = contentFile.readLine()) != null)
// System.out.println(s2);
// System.out.println("</TD>");
// }
System.out.println(s);
System.out.println(contentFlag);
}

Share: 

 

3 Answers Found

 
Answer #1    Answered By: Verner Fischer     Answered On: Apr 19

Can you replace the line if(s == contentFlag) with
if(s.equals(contentFlag)) and have a go at you
program.

 
Answer #2    Answered By: Luz Hayes     Answered On: Apr 19

it should read:
if( s.equals(contentFlag))

This will return true if the content of s and the
content of contentFlag are the same.

By putting if(s == contentFlag)
you are checking to see if s and contentFlag refer to
the same object.

 
Answer #3    Answered By: Vidos Fischer     Answered On: Apr 19

you're comparing if the two strings  are the same
reference not same "value" try s.equals(contentFlag)
that should give you your desired bahaviour.

 
Didn't find what you were looking for? Find more on problem with string comparison Or get search suggestion and latest updates.




Tagged: