有 Java 编程相关的问题?

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

为什么int a=5'0';在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
    }

对于这段代码,我有两个问题

  • 为什么int=5-'0';是可能的5是一个可以的int,但是在它旁边是一个字符,而不是为什么它没有抛出任何错误
  • 是结果的ASCII值吗?结果将如何计算

我知道43的ASCII值是+,但它会将'0'转换为ASCII,然后进行操作吗


共 (2) 个答案

  1. # 1 楼答案

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

    以上引语来自documentation。它清楚地说,char的最小值是0,最大值是65,535。Java提供了从charint的转换

    根据specification的说法:

    The values of the integral types are integers in the following ranges:(...)
    For char, from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535

  2. # 2 楼答案

    通过对int和char执行-操作,将使用char的ascii值(在您的示例中为48)。因此,表达式被转换为:

    int a = 5 - 48;