Signup/Sign In

Java Character equals() Method

Java equals() method belongs to the Character class. This method is used to compare the value of the Character object currently used with the value of the parameter. It has boolean as its return type i.e returns true if the value of the Character object is equal to the value of the parameter and returns false if the value of the Character object is not equal to the value of the parameter.

Note: This method overrides the equals() method of Object class. The syntax of the method is given below.

Syntax:

public boolean equals(Object obj)

Parameter:

The parameter passed is the Object which is to be checked for equality with the Character.

Returns:

It returns true if the value of Character object value is equal to the value passed as a parameter and returns false if the value of the Character object value is not equal to the value passed as parameter.

Example 1:

Here the Character objects ob1, ob2, ob3 are checked for equality by using the equals() method.

public class StudyTonight 
{  
    public static void main(String[] args) 
    {          
        Character ob1 = 'a'; 
        Character ob2 = 'b'; 
        Character ob3 = 'b';           
         //Checking for objects with equal and unequal values
        System.out.println("ob1 and ob2 equal?  "+ob1.equals(ob2));  
        System.out.println("ob2 and ob3 equal?  "+ob2.equals(ob3));                      
    }  
}  


ob1 and ob2 equal? false
ob2 and ob3 equal? true

Example 2:

Here is a user-defined example where anyone using this code can put a value of his choice and get the desired result.

import java.util.Scanner;  
public class StudyTonight 
{  
	public static void main(String[] args)
	{          
		try
		{
			Scanner sc = new Scanner(System.in);  
			System.out.print("Enter first character: ");  
			Character ch1 = sc.next().charAt(0);  
			System.out.print("Enter second character: ");  
			Character ch2 = sc.next().charAt(0);  
			boolean r = ch1.equals(ch2);  
			if (r==true)
			{               
				System.out.println("Same characters entered");  
			}  
			else
			{  
				System.out.println("Different characters entered");  
			}
		}
		catch(Exception e)
		{
			System.out.println("Invalid input!!Please check");
		}
	}  
}  


Enter first character: m
Enter second character: m
Same characters entered
************************************
Enter first character: c
Enter second character: j
Different characters entered

Live Example:

Here, you can test the live code example. You can execute the example for different values, even can edit and write your examples to test the Java code.



About the author:
A Computer Science and Engineering Graduate(2016-2020) from JSSATE Noida. JAVA is Love. Sincerely Followed Sachin Tendulkar as a child, M S Dhoni as a teenager, and Virat Kohli as an adult.