java compare characters code example

Example 1: compare 2 characters in java

public class JavaCharacterCompareExample1 {  
public static void main(String[] args) {  
char firstValue = 'A';  
char secondValue = 'B';  
// compare the first char to the second  
    int compareOneTwo = Character.compare(firstValue, secondValue);  
    if (compareOneTwo> 0) {  
    System.out.println("First value is greater than second value");  
    }  
    else {  
System.err.println("First value is less than second value.");  
    }  
   }  
}

// OUT:  First value is less than the second value.

Example 2: character comparison java

public static void compareCharacters(char c1,char c2){
	int cmp=Character.compare(c1,c2);
  	if(cmp>0){
    	System.out.println(c1+">"+c2);
    }else if(cmp<0){
    	System.out.println(c1+"<"+c2);
    }else{
    	System.out.println(c1+"="+c2);
    }
}

Example 3: how to compare two characters in java

If your input is a character and the characters you are checking against are mostly consecutive you could try this:

if ((symbol >= 'A' && symbol <= 'Z') || symbol == '?') {
    // ...
}

Tags:

Java Example