Java String Comparison


The String class includes a number of methods that compare strings or substrings within strings.

equals() and equalsIgnoreCase()


equals()

To compare two strings for equality, use equals(). It has this general form:

boolean equals(Object str)

Here, str is the String object being compared with the invoking String object. It returns true if the strings contain the same characters in the same order, and false otherwise. The comparison is case-sensitive.

Program
public class Main
{
	public static void main(String[] args) 
	{
		String s1="Hello";
		String s2="Hello";
		String s3="HELLO";
		
		System.out.println(s1+"equals"+s2+" -> "+s1.equals(s2));
		System.out.println(s2+"equals"+s3+" -> "+s2.equals(s3));
	}
}
Run

equalsIgnoreCase()

If you want to differentiate a case from a comparison, call the EqualIgnorecase () function. Comparing this with two strings makes A-Z equal to A-Z. It contains this simple form:

boolean equalsIgnoreCase(String str)

Here, the string object in the string is being compared to the invoking string object. This is also true if the strings contain the same letters in the same order and otherwise false.

Program
public class Main
{
	public static void main(String[] args) 
	{
		String s1="Hello";
		String s2="Hello";
		String s3="HELLO";
		
		System.out.println(s1+"equals"+s2+" -> "+s1.equalsIgnoreCase(s2));
		System.out.println(s2+"equals"+s3+" -> "+s2.equalsIgnoreCase(s3));
	}
}
Run

startsWith() and endsWith()

The startsWith() method determines whether a given String begins with a specified string. Conversely, endsWith() determines whether or not the String in question ends with a such as string. They have the following general forms:

boolean startsWith(String str)
boolean endsWith(String str)


Program
public class Main
{
	public static void main(String[] args) 
	{
		String s1="Hello";
		
		if(s1.startsWith("He"))
		{
		    System.out.println("Yes, s1 starts with He keyword");
		}
		else
		{
		    System.out.println("No, s1 not starts with He keyword");
		}
		if(s1.endsWith("lo"))
		{
		    System.out.println("Yes, s1 ends with lo keyword");
		}
		else
		{
		    System.out.println("No, s1 not ends with lo keyword");
		}
	    
	}
}
Run

equals() v/s ==

It is important to understand that the equals () function and the == operator perform two separate functions.. The equals() method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance.

Program
public class Main
{
	public static void main(String[] args) 
	{
		String f1="Hello";
		String f2=new String(f1);
		
		System.out.println(f1+" equals "+f2+" -> "+f1.equals(f2));
		System.out.println(f1+" == "+f2+" -> "+(f1==f2));
	}
}
Run