Line 16 of your code passes to the
checkFood method a
String object (because
junkfood from the command line is a String object), then line 25 compares this object with a literal from the String Pool. The problem is that this comparison is made through the
== operator, which actually doesn't check if two String objects have the same content, but if two String references point to the same object in memory. And in this case they obviously don't.
You said that by writing
checkFood("junkfood") it works correctly. That's because this time the comparison happens on two references that point to the same literal from the String Pool. But if you attempt to write
checkFood(new String("junkfood")), you will encounter the same problem, for the above reasons.
Remember:
always compare two strings with the
equal method!