I’m trying to add a function to my server’s code that checks the game version given in the packet that contains the username against the server’s game version. Even though the Strings appear to be exactly identical, an “if(connectionPacket.version == Display.version)” function returns false. Why is this? Is there a way to fix this?
str.equals(anotherStr);
or
str.equalsIgnoreCase(anotherStr);
if the case of the letters should be ignored.
Very common mistake for beginners
EDIT:
Why?
You check pointers with “==” not the content of the strings.
Another good one is string.compareTo(otherstring) if you want to know the order as well. I always use compareTo == 0 for matches, just out of habit.
Thanks, I didn’t think it was too complicated, i just was very confused.
It’s a nuance of Java that often takes a bit for coders from c/c++ and others to get the hang of. Everything is a pointer, basically, except primitives. Also there is no operator overloading, so comparisons always compare pointer values for everything that is not a primitive, thus the compareTo and equal methods are usually employed to compare the stuff in the objects you create, such as String. Just remember, if it’s a class then operators will effect the pointer, so look for the comparison methods. You can overload equal and if you implement the comparator interface you can add a compareTo as well, which is really helpful in sorting.
Personally, I prefer this nuance, it’s probably my favorite aspect of Java.