Compare two char values
In this chapter you will learn:
Compare two characters
int compareTo(Character anotherCharacter)
compares two Character objects numerically.boolean equals(Object obj)
compares this object against the specified object.
public class Main {
public static void main(String[] argv) {
Character character1 = new Character('a');
Character character2 = new Character('b');
System.out.println(character1.compareTo(character2));
}/* ja v a 2 s. co m*/
}
The output:
The following code makes the output more meaning full
by printing out different message for the result from compareTo
method.
public class Main {
public static void main(String args[]) {
Character a = new Character('a');
Character a2 = new Character('a');
Character b = new Character('b');
/*j a v a 2s.c o m*/
int difference = a.compareTo(b);
if (difference == 0) {
System.out.println("a is equal to b.");
} else if (difference < 0) {
System.out.println("a is less than b.");
} else if (difference > 0) {
System.out.println("a is greater than b.");
}
System.out.println("a is " + ((a.equals(a2)) ? "equal" : "not equal")
+ " to a2.");
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
Home » Java Tutorial » Primitive Data Types