Sam Sam - 1 month ago 5
Java Question

Why int a = 5 - '0'; is possible in java?

public static void main( String... args){
int a = 5 - '0';
System.out.println(a); //-43
Integer b = 5 - '0';
System.out.println(b); //-43
System.out.println(Integer.valueOf(a)); //-43
System.out.println(String.valueOf(b)); //-43
}


So I have two questions for this code.


  • Why
    int=5-'0';
    is possible??
    5
    is an int which is ok but next to that is a character than why it's not throwing any error??

  • Is it the ASCII value of result? than how result will be calculated?



I know ASCII value of
43
is
+
but is it will convert
'0'
to it's ASCII and then do the operation?

Answer

Doc:
char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

In this case it is casted to int, that is why it works.
Correction This is called Widening Primitive Conversion. Thanks @Andreas!

+1 curiosity

  public static  void main(String[] args) {
        int a = 5 - '0';
    }

I compiled this to bytecode:

  public static main([Ljava/lang/String;)V
   L0
    LINENUMBER 24 L0
    BIPUSH -43
    ISTORE 1
   L1
    LINENUMBER 25 L1
    RETURN
   L2
    LOCALVARIABLE args [Ljava/lang/String; L0 L2 0
    LOCALVARIABLE a I L1 L2 1
    MAXSTACK = 1
    MAXLOCALS = 2
}

Notice the line with BIPUSH -43 which means this value is calculated buildtime not runtime!

Comments