Comparing chars in Java
To compare two char
values in Java, you can use the ==
operator, just like you would with any other primitive type. For example:
char a = 'a';
char b = 'b';
if (a == b) {
System.out.println("a and b are equal");
} else {
System.out.println("a and b are not equal");
}
This will output a and b are not equal
.
You can also use the compareTo
method of the Character
class to compare two char
values. This method returns a negative integer if the first character is less than the second, a positive integer if the first character is greater than the second, and 0 if they are equal.
Here is an example of how to use the compareTo
method:
char a = 'a';
char b = 'b';
int result = Character.compareTo(a, b);
if (result < 0) {
System.out.println("a is less than b");
} else if (result > 0) {
System.out.println("a is greater than b");
} else {
System.out.println("a and b are equal");
}
This will output a is less than b
.