Do you know “How to compare two strings in Java?“
Well, if youโre curious to know about the comparison then this article is for you.
Here, we will look at different methods for string comparison in Java. The Java programming language introduces many ways for comparison of strings. You can use the one that fits the best in your project.
One of the logics that can help you understand Java is Java string comparison. So, let us get into comparing two Java strings.
Why Is It Important To Compare Two Strings In Java? Read Below
It is very important to compare Java string with another. It helps to understand the basics of the string objects.
Suppose, in a question, you are asked to operate & provide some output like comparing two Java strings. If you donโt know the possible methods to compare two strings,ย it will be very difficult for you.
Sometimes individuals want to know how to compare two strings in Java using the If statement or if else statement. ย Java is now a highly developed language. However, there are also many methods that help to find out the relation between two strings.
A string can be a field of the name, occupation, etc. It can be used to be a field for those cases that take a large statement. Sometimes for developing purposes, we need to compare two strings.
In such cases, we need to use some methods which are small in size. Methods that will take a large size in the code will not be proper implementation. That is why it is important to know the methods to compare one string to another in Java.
Also, itโs very important to know the basic difference between Comparable and Comparator in Java, if youโre not aware then you can read our article.
What Are Methods To Compare Two Strings In Java?
ย There exist a number of ways in which you can perform string comparisons. Maybe you can even come up with a whole new logic to do so, yourself.
In this article, we will look at 3 such methods to compare strings in Java. Let us now look at these methods below.
Some of these methods are the inbuild functions of the Java programming language. Using these methods not only helps you to shorten the code. But also it will be implemented by not using the If statement. The methods are:
- ย Using equals() method
- ย Using Equals-To (= =) operator
- ย Using comapreTo() method
ย Let us know about each method one by one briefly. Also, if youโre curious to know about the methods of comparing strings in Python then check out our article.
ย
How To Compare Two Strings In Java Using Equals() Method?
ย
To compare two string in Java using the equals() method, let us first create the string that we need to compare. In this case, we will be declaring three strings but we will compare two string objects at one time.
These are as:
string1 = โCodingZapโ
ย string2 = โZapOneโ
string3 =โCodingZapโ
Then we will use the equals() method. In this method, the first & the second string will be compared, and a boolean value is returned. After comparing, it will provide the value or results in the Boolean manner.
This means if both the strings are equal to each other, it will print the โtrueโ. If they are not equal to each other, then it will print โfalseโ.
Here, we have taken the first string & third string as โCodingZapโ & the second string as โZapOneโ. Comparing the strings between the first & second will provide the value as โfalseโ. As they are not equal. Comparing the first & third will print โtrueโ. As both of them are the same.
General Syntax: string1.equals(string2)
Code to compare strings in Java using Equals() method:
public class Main{
public static void main(String[] args) {
// Declaring The Strings
String s1="CodingZap";
String s2="ZapOne";
String s3="CodingZap";
// Comparing The First & Second Strings And Printing The Output
System.out.println("Comparing Between S1 & S2: "+ s1.equals(s2));
// Comparing The First & Third Strings And Printing The Output
System.out.println("Comparing Between S1 & S3: "+ s1.equals(s3));
}}
Letโs look at the output of the above code.
ย Output:
ย
How To Compare Two Strings In Java Using Equals-To (= =) Operator?
ย
ย Here, also we need to perform the same operations. We need to declare some strings for comparing purposes.
Let us keep the same three strings declared in the above program here as well.
Then we need to use the Equals-To (= =) operator. This is the same operator which helps to compare two numbers. This can also be used to compare a Java string to the second.
The equals to operator also provides the result in a Boolean manner. If both the strings are equal to each other, it will returnย โtrueโ. If the two strings are not equal to each other, then the operator will return โfalseโ.
Here we have taken the same example as in the above.ย So, it will provide the same result here also.
General Syntax:
string1 = = string2
Code Compare Two Strings In Java Using Equals-To (= =) Operator:
public class Main{
public static void main(String[] args) {
// Declaring The Strings
String s1="CodingZap";
String s2="ZapOne";
String s3="CodingZap";
// Comparing The First & Second Strings And Printing The Output
System.out.println(s1==s2);
// Comparing The First & Third Strings And Printing The Output
System.out.println(s1==s3);
}}
Letโs look at the output of the above program to see the working of the == operator.
Output:
ย
How To Compare Two Strings In Java Using The CompareTo() Method?
ย
Here, in this case, also, we have also taken some strings from comparing. This method is quite different. If the two strings are the same, then it will print the 0 as the result.
Suppose, the second string is less than the first string, then it will print some negative value. If the second string is greater than the first string then it will print a positive value.
Are you familiar with the strcmp() function in c? Well, the compareTo() method also works in a similar way. Let us understand about it through an example.
In this case, we have taken the same example as above. But here the result will be different. First, it will provide a negative value. As there is a length difference between two strings.
But the second output will be zero. As there is no length difference between s1 and s3.
General Syntax: string1.compareTo(string2)
Code To Compare Two Strings In Java Using The CompareTo() Method:
public class Main{
public static void main(String[] args) {
// Declaring The Strings
String s1="CodingZap";
String s2="ZapOne";
String s3="CodingZap";
// Comparing The First & Second Strings And Printing The Output
System.out.println("Comparing Between S1 & S2: "+ s1.compareTo(s2));
// Comparing The First & Third Strings And Printing The Output
System.out.println("Comparing Between S1 & S3: "+ s1.compareTo(s3));
}}
Letโs look at the output of the above code to understand the workings of the method.
Output:
Up till now, we have seen how we can compare two string objects using the built-in methods in Java.
But what if you are preparing for an interview and you get asked not to use these?ย
So, how to compare 2 strings without an in-built function? Is there any other way to do this comparison of two string objects in Java?
Yes, there is!
You can create a for loop with an if condition to compare one Java string with another. How? Letโs see.
Compare Java Strings without using Built-In Function
Ever thought about how to compare two strings using a for loop? Let us see what can be the approach to compare a Java string to another in this case.
ย So, to state it simply, we are going to define our own compareTo() method. We will iterate over the string using the for loop and also use conditional statements for the same.
ย This function will return the following on string comparison โย
- ย ย ย Case I โ string s1 < string s2:ย return negative value
- ย ย ย Case II โ string s1 > string s2: return positive value
- ย ย ย Case III –ย string s1 = string s2: if both strings are equal then return zero
ย You can say that we are going to compare strings using the if condition and for loop together for this purpose but with a twist. So if you are asked โhow to compare two strings in Java using if condition?โ Or, โhow to compare 2 strings in Java using for loop?โ follow the below-given code.
ย Consider the same strings as given in the above program. Let us now work on our function.
Code to compare Java strings using built-in function:
public class JavaStringCompare{
public static int compareStrings(String s1, String s2){
int lengths1 = s1.length();
int lengths2 = s2.length();
// find the minimum string length so that we know how many characters we can compare
int minlength = Math.min(lengths1, lengths2);
// iterating over strings using the for loop
for(int i=0; i
Now let us look at the output for the above program to see if it works.
ย Output:
All these ways compare two strings with case sensitivity. This means that both the strings should either be in upper case or lower case.ย
An example of this is if we compare โCodingZapโ with โcodingzapโ the result will say that the strings are not equal because they have different cases. So, how to compare two strings ignoring cases? Letโs see.
ย
How to compare two strings in Java ignoring case?
ย
Now, we will learn how to compare two strings in Java without case-sensitive or ignoring cases.
For this, we will use another method called equalsIgnoreCase(). This method compares one string object to another irrespective of their case. It also returns the result in boolean values.
General Syntax: s2.equalsignorecase(s1)
The string to be compared is in the parenthesis.
Code to compare strings in Java ignoring case:
public class Main{
public static void main(String[] args) {
// Declaring The Strings
String s1="CodingZap";
String s2="ZapOne";
String s3="codingzap";
// Comparing The First & Second Strings And Printing The Output
System.out.println("Comparing Between S1 & S2: "+ s2.equalsIgnoreCase(s1));
// Comparing The First & Third Strings And Printing The Output
System.out.println("Comparing Between S1 & S3: "+ s3.equalsIgnoreCase(s1));
}}
matrixData[i][j] = scanner.nextDouble();
} else {
throw new RuntimeException("Insufficient data in the file.");
}
}
}
Matrix matrix = new Matrix(matrixData);
matrix.print(); // Output the read matrix
} catch (FileNotFoundException e) {
System.err.println("File not found.");
}
}
Now let us see how it worked in the output below.
Since s1 and s3 are the same words i.e CodingZap, but with different type cases, we see that after ignoring the case, the result is true.ย
However, on comparison of s1 with s2, since the strings were not equal, the function returned false.
Output:
ย
How to compare if two strings in Java are Not Equal?
ย
For this, we will use the not equals operator. This is typed as (!=) It is the opposite of (==) operator and complements the boolean result value.ย
Let us see it’s working using the example.ย
Code to compare if the two strings in Java are not equal:
public class Main{
public static void main(String[] args) {
// Declaring The Strings
String s1="CodingZap";
String s2="ZapOne";
String s3="CodingZap";
// Comparing The First & Second Strings And Printing The Output
System.out.println(s1!=s2);
// Comparing The First & Third Strings And Printing The Output
System.out.println(s1!=s3);
}}
n("Comparing Between S1 & S3: "+ s3.equalsIgnoreCase(s1));
}}
matrixData[i][j] = scanner.nextDouble();
} else {
throw new RuntimeException("Insufficient data in the file.");
}
}
}
Matrix matrix = new Matrix(matrixData);
matrix.print(); // Output the read matrix
} catch (FileNotFoundException e) {
System.err.println("File not found.");
}
}
Since s1 and s2 in the above example are different, hence the (!=) operator will return the true value.ย
Let us confirm this below:
Conclusion:
As we saw comparing two strings in Java is very important to know.ย
When we are learning how to code as beginners, we have to clear the basics of the Java programming language to understand the concept in a good manner.ย
As per the choice of the individual, they can use any method mentioned above. It is a very useful implementation.
So, hope you have liked this piece of article. Share your thoughts in the comments section and let us know if we can improve more.
If you are looking for Final Year Java Project Ideas then you can contact us as well.