Java String equals() With Examples

Java String equals() method is used to compare this string with the passed object as argument.

Java String equals()

  • Java String equals() method overrides the Object class equals() method implementation.
  • Since String is immutable, checking the equality of string to another object should be done using equals() method rather than == operator.
  • String equals() method always return boolean value, it doesn’t throw any exceptions.
  • The result of equals() method is true if and only if – the argument is not null, it’s a String object, represents same sequence of characters as this string.
  • Below is the code snippet showing implementation details of equals() method.

    The method uses some of the internal classes and functions of String class, just have a look how it’s written in properly optimized way.
  • If you want case insensitive equality check, then you can use String equalsIgnoreCase() method. It’s signature is public boolean equalsIgnoreCase(String anotherString), note that here the argument is String object.

Java String equals() method example

Here is a short example of string equals() method.

Java String equalsIgnoreCase() method example

Here is a short code snippet showing how to use equalsIgnoreCase() method.

Java String equals() example with user input

Here is an example where two strings are compared using equals() and equalsIgnoreCase() methods. Both of these string are entered by user on command prompt and we are using Scanner class to read them.

Here is a sample output produced when above program is executed in Eclipse IDE.

Java String equals method example

That’s all for Java String equals() method usage and examples.

Reference: API Doc

By admin

Leave a Reply