How to compare characters in a string in Java code example

Example 1: java how to compare strings

System.out.println("hey".equals("hey")); //prints true

/*
	always use .equals() instead of ==,
    because == does the compare the string content but
    loosely where the string is stored in.
*/

Example 2: 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 3: in java how to compare two strings

class scratch{
    public static void main(String[] args) {
        String str1 = "Nyello";
        String str2 = "Hello";
        String str3 = "Hello";

        System.out.println( str1.equals(str2) ); //prints false
        System.out.println( str2.equals(str3) ); //prints true
    }
}

Example 4: 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