Search code examples
javadigits

Character.isDigit is returning different results in conditional operator


Code 1 returns 1.

Code 2 returns 49.

Shouldn't they return the same result?

public class MyClass {
    public static void main(String args[]) {
        String code = "1";
        StringBuilder digitSB = new StringBuilder();
        for(int i = 0; i < code.length(); i++){
            char chr = code.charAt(i);
            //Code 1
            if(Character.isDigit(chr)){
                digitSB.append(chr);
            }
            else{
                digitSB.append(Character.getNumericValue(chr));
            }
            System.out.println("Code 1 result: " + digitSB);
            //Code 2
            digitSB = new StringBuilder();
            digitSB.append(Character.isDigit(chr) ? chr : Character.getNumericValue(chr));
            System.out.println("Code 2 result: " + digitSB);
        }
    }
}

Note that 49 is the ASCII code of 1.

Edit: It's as @matt said in the comments. When you use the ternary operator, both sides of the ":" are considered the same type. Since getNumericValue assumes it's an int, both sides are an int. The condition is true, so it takes the left side, which is chr, but considers it an int.


Solution

  • Return type treated as int in case of ternary operator. Use like this

    Character.isDigit(chr) ? chr : ""+ Character.getNumericValue(chr);
    
    

    or

    Character.isDigit(chr) ? ""+chr :  Character.getNumericValue(chr);