zombiecircus zombiecircus - 6 months ago 18
Java Question

jave spring string equals return false when they seem to be the same when printing

I'm working on an eclipse project using java spring for a website. However, no matter what I tried, the following string seems to be different. Would be great if someone can tell me what to do.

@RequestMapping(value = "/result", method = RequestMethod.GET)
public ModelAndView execute(@ModelAttribute("dummyForm") final DummyForm dummyForm, final Model model) {
// ...
final String str = dummyForm.getFirstName() + "_" + dummyForm.getLastName();
// ...
return mav;

with this code, when I test with dummyForm.setFirstName("Dummy") and dummyForm.setLastName("Smith"):
printing "str" in jsp will show "Dummy_Smith" as expected. But at the if condition check, it always returns false.
I tried doing str.compareTo("Dummy_Smith"), and it returns -33.
What should I do if I want it to return true?

Thanks in advance.


My bet is that there are either whitespace or invisible characters in the string so that when you print it looks like they are the same string but they are not, actually, the same. Try to trim out any whitespace from the string you are comparing to and see what it returns:

String trimmed = str.trim();

A true value from the compareTo call is if the value is equal to 0 (so the second printed line above).