Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java compareTo() Method

Java compareTo() Method

Java String ClassJava String class


The compareTo() method is used for two ways of comparison:

Syntax

int

compareTo

(

Object

o

)

or

int

compareTo

(

String

anotherString

)

Parameters

Return Value

The return value is an integer. It first compares the sizes of the corresponding characters (in ASCII order). If the first character and the first character of the argument are different, the comparison ends and returns the difference in theirlengthsIf the first character and the first character of the argument are equal, then the second character is compared with the second character of the argument, and so on, until one of the compared strings ends.

Explanation:

If the first character and the first character of the argument are different, the comparison ends and returns the ASCII code difference of the first character.

If the first character and the first character of the argument are equal, then the second character is compared with the second character of the argument, and so on, until they differ, then the ASCII code difference of that character is returned. If the two strings are of different lengths but their corresponding characters are identical, the difference in length of the two strings is returned.

Example

public

class

Test

{

public

static

void

main

(

String

args

[

]

)

{

String

str1

=

"

Strings

"

;

String

str2

=

"

Strings

"

;

String

str3

=

"

Strings123

"

;

int

result

=

str1

.

compareTo

(

str2

)

;

System

.

out

.

println

(

result

)

;

result

=

str2

.

compareTo

(

str3

)

;

System

.

out

.

println

(

result

)

;

result

=

str3

.

compareTo

(

str1

)

;

System

.

out

.

println

(

result

)

;

}

}

The execution result of the above program is:


0
-3
3

Java String ClassJava String class