Java: Subtract '0' from char to get an int… why does this work?

前端 未结 9 664
伪装坚强ぢ
伪装坚强ぢ 2020-11-27 05:04

This works fine:

int foo = bar.charAt(1) - \'0\';

Yet this doesn\'t - because bar.charAt(x) returns a char:

int foo = bar.c         


        
9条回答
  •  孤城傲影
    2020-11-27 05:18

    Your second snipped should work fine though:

    int foo = bar.charAt(1);
    

    A char, just like a short or byte, will always be silently cast to int if needed.

    This will compile just fine: int i = 'c';

提交回复
热议问题