I wanted to compare a string without actually defining one of them as a string, something like this,
if (string == "add")
Do I have to declare "add"
as a string or is it possible to compare in a similar way?
The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
In C++ the std::string
class implements the comparison operators, so you can perform the comparison using ==
just as you would expect:
if (string == "add") { ... }
When used properly, operator overloading is an excellent C++ feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With