Search code examples
javamethodscastingcharshort

java why char to short is possible in method return type


I have the following method in Java:

private static short charToShort_1() {
    return 's';
}

private static char shortToChar_1() {
    return ((short) 15);
}

private static short charToShort_2() {
    char ch = 's';
    return ch;
}

private static char shortToChar_2() {
    short number = 15;
    return number;
}

Why "charToShort_1" and "shortToChar_1" are compiled successfully?
In the same time the last two methods "charToShort_2" and "shortToChar_2" can not be compiled (because explicit cast is necessary).


Solution

  • Here :

    private static short charToShort_1() {
        return 's';
    }
    

    's' is a constant expression and this value is representable in short. So the compiler does an implicit conversion.

    The JLS states :

    In addition, if the expression is a constant expression (§15.28) of type byte, short, char, or int:

    • A narrowing primitive conversion may be used if the type of the variable is byte, short, or char, and the value of the constant expression is representable in the type of the variable.

    The short values range is -32,768 to 32,767 (inclusive).
    So a constant expression char out of these bounds will produce a compilation error :

    private static short charToShort_2() {
       return '耀'; // 32768 numeric value       
    }
    

    About this method that doesn't compile :

    private static short charToShort_2() {
        char ch = 's';
        return ch;
    }
    

    char ch = 's'; is not a constant expression.
    You may reassign ch with a new char value that is not representable in short (such as '耀' that is represented by the 32768 numeric value).
    So the compiler expects you explicitly cast it to short as the conversion may be a narrowing primitive conversion.
    Change it into a final variable and you will see that it compiles fine :

    private static short charToShort_2() {
        final char ch = 's';
        return ch;
    }
    

    About this method that casts from short to char, the compilation error reason is exactly the same as for charToShort_2()

    At last, about shortToChar_1() :

    private static char shortToChar_1() {
        return ((short) 15);
    }
    

    The cast to short may give the impression that you spend less memory than if you had used a int:

    private static char shortToChar_1() {
        return 15;
    }
    

    In fact, it doesn't change anything as in both cases the compiler will use the bipush JVM instruction to push a byte onto the stack as an integer value.