Is there a default type for numbers in Java

前端 未结 2 2039
南旧
南旧 2020-11-28 15:39

If I write something like this

System.out.println(18);

Which type has the \'18\'? Is it int or byte? Or doesn\'t it have

相关标签:
2条回答
  • 2020-11-28 16:02

    This

    18
    

    is known as an integer literal. There are all sorts of literals, floating point, String, character, etc.

    In the following,

    byte b = 3;
    

    the literal 3 is an integer literal. It's also a constant expression. And since Java can tell that 3 fits in a byte, it can safely apply a narrowing primitive conversion and store the result in a byte variable.

    In this

    int i = 3;
    byte bb = i; //error!
    

    the literal 3 is a constant expression, but the variable i is not. The compiler simply decides that i is not a constant expression and therefore doesn't go out of its way to figure out its value, a conversion to byte may lose information (how to convert 12345 to a byte?) and should therefore not be allowed. You can override this behavior by making i a constant variable

    final int i = 3;
    byte bb = i; // no error!
    

    or by specifying an explicit cast

    int i = 3;
    byte bb = (byte) i; // no error!
    
    0 讨论(0)
  • 2020-11-28 16:13

    The JLS-4.2.1 - Integral Types and Values

    The values of the integral types are integers in the following ranges:

    • For byte, from -128 to 127, inclusive
    • For short, from -32768 to 32767, inclusive
    • For int, from -2147483648 to 2147483647, inclusive
    • For long, from -9223372036854775808 to 9223372036854775807, inclusive
    • For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535

    And JLS-3.10.1 - Integer Literals

    An integer literal is of type long if it is suffixed with an ASCII letter L or l (ell); otherwise it is of type int (§4.2.1).

    Finally, JLS-3.10.2 - Floating-Point Literals includes

    A floating-point literal is of type float if it is suffixed with an ASCII letter F or f; otherwise its type is double and it can optionally be suffixed with an ASCII letter D or d (§4.2.3).

    As for byte b = 3; it is a Narrowing Conversion from int to byte.

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