Java String Equals Sample Code

Often times in Java programming you will need to compare two Strings. The Java String class comes with the equals() method and the equalsIgnoreCase() method. Both methods compare two Strings, but act slightly different.

The equals() method will compare two String and if both Strings are completely equivalent.
The equalsIgnoreCase() method will also compare two Strings to be equal, but will completely ignore the case of both Strings.

Both methods will return true if the Strings are not null and are equal based on their own criteria.

Class Name Method Parameters Return Type Exceptions
String equals() Object boolean none
String equalsIgnoreCase() String boolean none

Java String Equals Source Code:

package com.jcd.java.tutorials;

public class JavaStringEquals 
{

	public static void main(String[] args) 
	{

		//Define String A upper case
		String myStringAUpper = "SMEDLEY";
		
		//Define String A lower case
		String myStringALower = "smedley";
		
		
		//Check equality with keeping case
		System.out.println("Comparing with equals(): "+myStringAUpper+" and "+myStringALower);
		
		if(checkEquality(myStringAUpper, myStringALower))
		{
			System.out.println("Strings are EQUAL using equals() method");
		}
		else
		{
			System.out.println("Strings are NOT EQUAL using equals() method");
		}
		
		System.out.println("------------------------------------------------------------------");
		
		//Check equality ignoring case
		System.out.println("Comparing with equalsIgnoreCase(): "+myStringAUpper+" and "+myStringALower);
		
		if(checkEqualityIgnoreCase(myStringAUpper, myStringALower))
		{
			System.out.println("Strings are EQUAL using equalsIgnoreCase() method");
		}
		else
		{
			System.out.println("Strings are NOT EQUAL using equalsIgnoreCae() method");
		}		

	}
	
	//Method to see if strings are equal keeping case
	public static boolean checkEquality(String str1, String str2) 
	{
		if(str1.equals(str2))
		{
			return true;
		}
		else 
		{
			return false;
		}
	}
	
	//Method to see if strings are equal ignoring case
	public static boolean checkEqualityIgnoreCase(String str1, String str2) 
	{
		
		if(str1.equalsIgnoreCase(str2))
		{
			return true;
		}
		else 
		{
			return false;
		}
	}

}


Java String Equals Output:

Comparing with equals(): SMEDLEY and smedley
Strings are NOT EQUAL using equals() method
------------------------------------------------------------------
Comparing with equalsIgnoreCase(): SMEDLEY and smedley
Strings are EQUAL using equalsIgnoreCase() method


References:

Add a Comment

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