In this java tutorial, we will learn how do I compare strings in java. where we have two strings we can compare simply with an inbuilt method .equals() or by simply applying ‘==’ operators where it will compare two strings.
What Is String?
The string is an immutable value that can not be edited once it is declared so we need to declare it as we are doing so for the last time for a comparison of two variables to the concern we can compare two strings by simply different in build function or operation and methods.
So let’s discuss some of the ways to do so.
Comparing using .equals()
If the we simply wants to compare two string on the basis of the characters present in the string we can do o only by using the inbuild method .equals() which helps us in get the result in boolean as true or false as it is used for returning the values in true and false only.
Lets understand the situation using an example:
In the given example we can say there two strings are compared using .isequals() method which gives yes as both the strings are the same here we can conclude that if uses the String as it is to compare two and return True or False.
Comparing Using ‘==’ Operators
There is another way to compare two strings where is does not compare the string as a string whereas it uses the reference to compare two strings lets understand this also using some examples.
Although it is also used for comparing two strings their uses in different situations make them different from each other so let’s make some different out here between the ways of comparing the strings..
String fooString1 = new String("foo"); String fooString2 = new String("foo"); // Evaluates to false fooString1 == fooString2; // Evaluates to true fooString1.equals(fooString2); // Evaluates to true, because Java uses the same object "bar" == "bar"
As in the example given above we can see how the result of the first comparison using ‘==’ is giving the answer as false as it does not deal with the string strictly not with the variable – variable, Variable – value whereas it deals with value- values.
as a result in the case of the third example, it will give a true result as there we are directly comparing the string instate of variables. This makes the .equals() and ‘==’ different from each other as a result we use both of them at different places.
Learn More about How do I compare strings in Java? : Compare String
And learn More at :JAVA TUTORIAL