java string compare – How to compare strings in java

Java string comparison

Java provides a few methods by which strings can be compared. The methods are:

  1. Using equals method
  2. Using compareTo method

Each of these methods explained below with example.

String comparison by equals() method

The java String class method equals() is used to compare two strings whether two are the same or not.

A few main points about equals method:

  • The equal method is used to compare two strings
  • In equals method strings are compares as case sensitive i.e. “Java” and “java” are different
  • The return result is True is strings are same
  • The return result will be false if strings are not same

Syntax of equals method

The syntax of equals method is:

Strex.equals(Strex2)

Where Strex and Strex2 are two strings being compared.

Example of using equals method in java

The example below uses equals method that compares two strings. Total three string objects are used and compared in two Boolean variables with equals method. See the result below:



See graphic of above example

The output will be:

String 1 and 2 are equal? false

String 1 and 2 are equal? True

The first result is false as ‘s’ is small in first string.

String comparison by compareTo() method

The compareTo() method also takes two strings to be compared however unlike equals() method it returns an int value.

  • If two strings are equal the return result will be 0.
  • If string one is greater than string two, the return result will be positive.
  • If string one is less than string two the returned result will be negative.

Example of using compareTo method



See graphic of above example

The output will be:

Returned value: 0

Returned value: 10

Returned value: -10

Also see Java Strings

Was this article helpful?

Related Articles

Leave A Comment?