+ 2

Why if statement doesn't work with splitted String?

So in this code, https://code.sololearn.com/c2uf18bX9uN2/?ref=app I made a string "WordOne WordTwo", then splitted it with split method, then checked with it statement if one of the splitted words equals another string, and if statement doesn't work for some reason. And if I don't use split method and just make a string array, and check if it equals to another string, it works! That's so confusing...

2nd Jul 2022, 8:58 PM
Super Ant
Super Ant - avatar
4 Answers
+ 1
For String comparisons, use equals() method.. == opearator compares reference, while equal () method compare contents in java.. Ex: if(splitWords[0].equals("WordOne")){
2nd Jul 2022, 9:34 PM
Jayakrishna 🇼🇳
+ 1
Ok, but how the second part of code without split method is working and first one is not?
2nd Jul 2022, 9:36 PM
Super Ant
Super Ant - avatar
+ 1
Because they will have same references in the string constant pool.. You can check thier hashcodes, would be same. and == operator compare references for non-primitive objects.. hope it helps..
2nd Jul 2022, 9:42 PM
Jayakrishna 🇼🇳
+ 1
Yes, that helped, thanks
2nd Jul 2022, 9:55 PM
Super Ant
Super Ant - avatar