如何在Java中比较字符
在本文中,我们将比较Java中的字符。
爪哇 provides some built-in methods such 相比()
and 等于()
to 相比 the 烧焦acter objects. Although, we can use less than or greater than operators but they work well with primitive values only.
让’我们以一些示例比较Java中的字符。
比较原始字符
You can 相比 primitive 烧焦s either using 字符.compare()
method or <, > or =
relational operators.
使用compare()
The 相比()
method of 字符s 类 returns a numeric value positive, negative or zero.
请参见下面的示例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
类 主要 { 上市 静态的 虚空 主要(串[] args){ 烧焦 a = '一个'; 烧焦 b = 'b'; 如果 (字符.相比(a, b) > 0) { 系统.出.打印(“更大”); }其他 如果 (字符.相比(a, b) < 0) { 系统.出.打印(“ a小于b”); }其他 系统.出.打印(“两者平等”); } } |
输出量
使用关系运算符
我们可以使用小于或大于的关系运算符来比较Java中的两个字符。这是最简单的方法,并且不涉及任何类或方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
类 主要 { 上市 静态的 虚空 主要(串[] args){ 烧焦 a = '一个'; 烧焦 b = 'b'; 如果 (a > b) { 系统.出.打印(“更大”); }其他 如果 (a < b) { 系统.出.打印(“ a小于b”); }其他 系统.出.打印(“两者平等”); } } |
输出量
比较角色对象
You can 相比 primitive 烧焦s either using 字符.compare()
method or 等于()
method.
使用compare()
You can use 相比()
method with 字符 objects as well. The 相比()
method of 字符s 类 returns a numeric value positive, negative or zero.
请参见下面的示例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
类 主要 { 上市 静态的 虚空 主要(串[] args){ 字符 ch1 = 'X'; 字符 ch2 = 'y'; 如果 (字符.相比(ch1, ch2) > 0) { 系统.出.打印(“ x更大”); }其他 如果 (字符.相比(ch1, ch2) < 0) { 系统.出.打印(“ x小于y”); }其他 系统.出.打印(“两者平等”); } } |
输出量
使用Equals()
The 等于()
method is used to check whether two 烧焦 objects are equal or not. It returns true
如果 both are equal 其他 returns false
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
类 主要 { 上市 静态的 虚空 主要(串[] args){ 字符 a = '一个'; 字符 b = 'b'; 如果 (a.等于(b)) { 系统.出.打印(“ a等于b”); }其他 系统.出.打印(“ a不等于b”); } } |
输出量
那’关于如何在Java中比较字符的全部内容。