• Post Reply Bookmark Topic Watch Topic
  • New Topic

if (String == String)  RSS feed

 
Andrew M.
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello...
I'm having troubles comparing strings in an if statement...
I have a file that I have read (line by line) and then tokenized with StringTokenizer.
Now, the second token of every line is either the letter P or S (a sales spreadsheet, P stands for produced, and S for sales).
But, when I take the token and assign it to a String variable I cannot compare it to a P or S in an If statement.
transtype = str.nextToken();
if (transtype == "P"){...
Now... I know that token is A)a string, and B)the letter P (capitalized, if it matters).
However, when the program runs it completely ignores the If statement, as if the if failed.
Why can't I compare them...
Thanks for any help!
-Andrew
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you compare objects with "==" the reference address is compared
not the content. If you want to campare the content of the string
use:
"P".equals(yourString)
Then it should work as expected
 
Andrew M.
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simple and effective...
Thank you so much...
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andrew M.,
Welcome to JavaRanch!
We ain't got many rules 'round these parts, but we do got one. Please change your display name to comply with The JavaRanch Naming Policy.
An initial isn't enough for a dislayed last name.
Thanks Pardner! Hope to see you 'round the Ranch!
 
Chengwei Lee
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose you've 2 strings, "Hello World" & "hello world", do you consider them to be the same?

If you do, the equals() method won't quite work. Use the equalsIgnoreCase() method instead.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!