A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://howtodoinjava.com/java/string/java-string-compareto-method/ below:

Java String compareTo()

Java String.compareTo() compares two strings lexicographically (in dictionary order) in a case-sensitive manner. For case-insensitive comparison, use compareToIgnoreCase() method.

1. Strings in Lexicographic Order

If a string 'string1' comes before another string 'string2' in the dictionary, then string2 is said to be greater than 'string1' in string comparison.

2. String.compareTo() API

The compareTo() function takes one argument of type String. The second string is the String object itself, on which method is called. Note that compareTo() does the string comparison based on the Unicode value of each character in the strings.

int result = string1.compareTo(string2);

The result of this method is in integer value where –

3. Java Program to Compare Strings

The following Java program compares two strings case-sensitively using the compareTo() method. We ae using Hamcrest matches to assert the return values.

String name = "alex";

//same string
assertThat(name.compareTo("alex"), equalTo(0));

//Different cases
assertThat(name.compareTo("Alex"), greaterThan(0));
assertThat(name.compareTo("ALEX"), greaterThan(0));

//Different strings
assertThat(name.compareTo("alexa"), lessThan(0));
assertThat(name.compareTo("ale"), greaterThan(0));
4. Difference between compareTo() and equals()

The differences between compareTo() and equals() methods are:

Happy Learning !!

Reference: String Java Doc


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4