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

前端 未结 9 594
伪装坚强ぢ
伪装坚强ぢ 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:11

    The following code works perfectly fine!

    int foo = bar.charAt(1);
    

    Similar to reference types, any Java primitive can be assigned without casting to another primitive of a type it is considered a subtype of. The subtyping rules for primitives are given by JLS section 4.10.1. char is considered a subtype of int, so any char may be assigned to an int.

    0 讨论(0)
  • 2020-11-27 05:14

    Because in Java if you do not specify a type indicator with a number then it assumes Integer. What I mean by that, if you want to set a Long value, it would need to be 0L.

    Performing a numerical operation on two different numerics, the result takes the larger. Hence, a char (which is a numerical value) minus an integer, results in an integer.

    You will find that this works also

    long val = bar.charAt(1) - 0L;
    
    0 讨论(0)
  • 2020-11-27 05:16

    '0' is a char too. It turns out, the characters in Java have a unicode (UTF-16) value. When you use the - operator with characters Java performs the operation with the integer values.

    For instance, int x = '0' - 'A';// x = 16

    0 讨论(0)
  • 2020-11-27 05:17

    chars are converted to int implicitly:

       public static void main(String [] args) throws Exception {
         String bar = "abc";
         int foo = bar.charAt(1) - '0';
         int foob = bar.charAt(1);
         System.err.println("foo = " + foo + "   foob = " + foob);
       }
    

    output: foo = 50 foob = 98.

    Maybe you put two int foo ... and this is because it didn't work?

    0 讨论(0)
  • 2020-11-27 05:18

    This is an old ASCII trick which will work for any encoding that lines the digits '0' through '9' sequentially starting at '0'. In Ascii '0' is a character with value 0x30 and '9' is 0x39. Basically, i f you have a character that is a digit, subtracting '0' "converts" it to it's digit value.

    I have to disagree with @Lukas Eder and suggest that it is a terrible trick; because the intent of this action aproaches to 0% obvious from code. If you are using Java and have String that contains digits and you want to convert that String to an int I suggest that you use Integer.parseInt(yourString);.

    This technique has the benifit of being obvious to the future maintenance programmer.

    0 讨论(0)
  • 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';

    0 讨论(0)
提交回复
热议问题