Friday 12 July 2019

java - Why doesn't my string comparison work?

Your second comparison is wrong. You should also use equals instead of ==, like this:




if (action.trim().equals("something"))


The == operator compares references of (String) objects and under normal circumstances equal strings don't automatically have the same reference, i.e. they are different objects. (Unless both are internalized, but normally you shouldn't consider it)



Other than that your example works fine and the first comparison is valid. Try fixing the second comparison. If it works, you found your problem. If not, try using a debugger and double-check everything.



PS: When comparing literal strings with dynamic string objects, it's good practice to call the equals method on the literal string:



"something".equals(action)



That way you can avoid NullPointerExceptions when the string object is null.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...