How to Compare Two Strings in Java?

how to compare two strings in java

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.

How to compare two strings in Java?

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.

Methods to compare strings in Java

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:

  1.   Using equals() method
  2.   Using Equals-To (= =) operator
  3.   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:

Comparing strings using Equals() method 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:

Comparing Equals-To() 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:

Compare() to 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<minlength; i++){
        	//now we need to compare each character in the string
        	char s1char = s1.charAt(i);
        	char s2char = s2.charAt(i);
        	
        	// using if to compare both characters
        	if(s1char != s2char){
            	return s1char-s2char;
        	}
    	}
    	if (lengths1 != lengths2){
        	return lengths1-lengths2;
    	}
    	else{
        	return 0;
    	}
    	
    }
 	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: "+ compareStrings(s1, s2));
 
    	// Comparing The First & Third Strings And Printing The Output
 
      	System.out.println("Comparing Between S1 & S3: "+ compareStrings(s1, s3));
 
    }
}

                        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 look at the output for the above program to see if it works.

 Output:

Compare Java Strings without using Built-In Function 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:

Compare strings in Java ignoring case 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:


Compare strings if not equal output

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.

hire us for best programming homework help

Leave a Comment

Your email address will not be published. Required fields are marked *