How to compare two strings in java using equals and equalsIgnoreCase functions?



Compare two strings in java using equals and equalsIgnoreCase functions



/* Program to compare two strings ... From technology-mantra.blogspot.in */

public class compare
{
public static void main(String args[])
{
String s1 = "iamthebest";
String s2 = "IAMTHEBEST";
boolean result;

result = s1.equals(s2);
System.out.println("Result is : " + result);

result = s1.equalsIgnoreCase(s2);
System.out.println("Result of Ignore case is : " + result);

}
}

OUTPUT


Result is : FALSE
Result of Ignore case is : TRUE

DOWNLOAD THIS PROGRAM


In this program we used equals() and equalsIgnoreCase() functions of java to compare strings.

Details about equals() function



Syntax :
public boolean equals(Object anObject)

Parameters

This function takes an object (string variable) to be compared as a parameter

How to call
create two string variables which you want to compare

String s1 = "abc";
String s2 = "ABC";

Now create a boolean variable to store output result of this function, this function returns boolean value that's why we are storing the return value in boolean variable.

boolean result;

Now call this function like this =>

result = s1.equals(s2);

Return value

This function returns true if both of the strings are equal. It is case sensitive function i.e it considers "A" and "a" both are different.

Whats happening in the program

In the program we used equals() function to compare two string variables s1 and s2. It returned the boolean value "FALSE" because the strings stored in s1 and s2 variables are not same (case sensitivity)




Details about equalsIgnoreCase() function



Syntax
public boolean equalsIgnoreCase(Object anObject) 


Parameters

This function takes an object (string variable) to be compared as a parameter

How to call

create two string variables which you want to compare

String s1 = "abc";
String s2 = "ABC";

Now create a boolean variable to store output result of this function, this function returns boolean value that's why we are storing the return value in boolean variable.

boolean result;

Now call this function like this =>

result = s1.equalsIgnoreCase(s2);

Return value

This function returns true if both of the strings are equal. It is not case sensitive function i.e it considers "A" and "a" both are same.

Whats happening in our program

In the program we used equalsIgnoreCase() function to compare two string variables s1 and s2. It returned the boolean value "TRUE" because the strings stored in s1 and s2 variables are same.
Share on Google Plus

About Unknown

Hrishabh Sharma is the founder of an IT firm "Chanakya IT Solutions" that offers a variety of software,website,mobile-app solutions. He has more than 7 years of experience in software and web development. You can contact him at FACEBOOK or Send email at hrs.king@yahoo.in
    Blogger Comment
    Facebook Comment

1 comments: