有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java中是否有数字的默认类型

如果我写这样的东西

System.out.println(18);

哪种类型有“18”? 是int还是字节? 还是它还没有定型

它不可能是int,因为这样是正确的:

byte b = 3;

这是不正确的:

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

编辑: 我想我在Assignment Conversion的规范中找到了正确的部分:

The compile-time narrowing of constants means that code such as:

byte theAnswer = 42;

is allowed. Without the narrowing, the fact that the integer literal 42 has type int would mean that a cast to byte would be required:

byte theAnswer = (byte) 42; // cast is permitted but not required


共 (3) 个答案

  1. # 1 楼答案

    这个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

    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).

    最后,JLS-3.10.2 - Floating-Point Literals包括

    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).

    至于byte b = 3;,它是从intbyteNarrowing Conversion

  2. # 2 楼答案

    正如其他人所说,它是一个整数文本

    在幕后,Java似乎是为32位处理器编写的。 一个整数介于+/-~214.7万之间,即2^31,带一个标志位

    所以无论你是写一位还是一个完整的int,它都是一个单处理器函数,因此是一个单内存分配

  3. # 3 楼答案

    这个

    18
    

    被称为integer literal。有各种各样的literals、浮点、String、字符等等

    在下文中

    byte b = 3;
    

    文本3是一个整数文本。这也是一个恒定的表达式。由于Java可以判断3适合byte,因此它可以安全地应用narrowing primitive conversion并将结果存储在byte变量中

    在这个

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

    文字3是一个常量表达式,但变量i不是。编译器只是决定i不是一个常量表达式,因此不会特意计算它的值,对byte的转换可能会丢失信息(如何将12345转换为byte?)因此不应该被允许。可以通过将i设为常量变量来覆盖此行为

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

    或者通过指定显式强制转换

    int i = 3;
    byte bb = (byte) i; // no error!