Java.lang.Character.compareTo() 方法
描述
java.lang.Character.compareTo(Character anotherCharacter) 比较两个 Character 对象的数值。
声明
以下是 java.lang.Character.compareTo() 方法的声明。
public int compareTo(Character anotherCharacter)
指定者
接口 Comparable<Character> 中的 compareTo
参数
anotherCharacter − 要比较的字符
返回值
如果参数 Character 等于此 Character,此方法返回值 0,如果此 Character 在数值上小于 Character 参数,则返回值小于 0; 如果此 Character 在数值上大于 Character 参数(无符号比较),则值大于 0。 这是严格的数字比较; 它不依赖于语言环境。
异常
NA
示例
下面的例子展示了 lang.Character.compareTo() 方法的使用。
package com.tutorialspoint;
import java.lang.*;
public class CharacterDemo {
public static void main(String[] args) {
// create 2 Character objects c1, c2
Character c1, c2;
// assign values to c1, c2
c1 = new Character('a');
c2 = new Character('b');
// create an int type
int res;
// compare c1 with c2 and assign result to res
res = c1.compareTo(c2);
String str1 = "Both values are equal ";
String str2 = "First character is numerically greater";
String str3 = "Second character is numerically greater";
if( res == 0 ) {
System.out.println( str1 );
} else if( res > 0 ) {
System.out.println( str2 );
} else if( res < 0 ) {
System.out.println( str3 );
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
Second character is numerically greater

