Johan
Johan

Reputation: 425

comparing uppercase and lowercase using compareTo() method in java

I want to compare uppercase and lowercase using compareTo() method in java. Below is the code snippet I have used but not able to understand why it is returning 32.

String s1="a"; 
String s2="A";
System.out.println(s1.compareTo(s2)); 
//return 32

Upvotes: 0

Views: 6766

Answers (2)

Whitefret
Whitefret

Reputation: 1067

Java – String compareTo() Method example. The method compareTo() is used for comparing two strings lexicographically. Each character of both the strings is converted into a Unicode value for comparison. If both the strings are equal then this method returns 0 else it returns positive or negative value.

So `'a' - 'A' => 97 - 65 = 32

Upvotes: 0

CMPS
CMPS

Reputation: 7769

s1.compareTo(s2)

Will do:

'a' - 'A' => 97 - 65 = 32

From Java docs:

the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

Upvotes: 4

Related Questions