【问题标题】:Concatenation of different types in JavaJava中不同类型的连接
【发布时间】:2021-04-19 18:18:48
【问题描述】:

我知道,问题很简单。但是有一些小细节我需要完全理解(理解背景中发生的事情非常重要)。我们先来看看片断代码。为什么这里连续 2 个“+”号不会导致错误?或者这两个“+”之间是否有一个不可见的 0?在第一种情况下,字符被转换为整数的原因是两个连续的“+”号,对吧?

public class AppleApp {
    public static void main(String[] args) {
        System.out.println("Apple is " + + '2' + " USD");
        // OUTPUT:   Apple is 50 USD
        System.out.println("Apple is " + + 2 + " USD");
        // OUTPUT:   Apple is 2 USD
    }
}

【问题讨论】:

    标签: java string casting formatting


    【解决方案1】:

    "Apple is " + + 2 + " USD" 被“解析”如下:

    ("Apple is " + (+2) + " USD"+2 只是.. 2. 就像 int x = +2; 是合法的一样。

    这同样适用于+ + '2',因为在 java 中,字符是数字(即使是字符串)也不是。 '2' 是数字 0x32(字符 2 的 unicode 代码)。


    char 有点奇怪;它是数字。具体来说,char 代表 0 到 65535 之间的数字,就像 byte 是 -128 到 +127,short 是 -32768 到 +32767,int 是 -2147483648 到 2147483647。

    尽管它是一个数字,但所有打印事物的相关方法都将数字视为 unicode 值:它们在 unicode 表中查找数字并显示字符,即:

    char c = 65;
    System.out.println(c);
    

    打印A。这不是因为 char 中固有的任何东西,而是因为 println 方法。

    在 java 中,byteshortchar 比较差:很多操作不能对它们进行,而是都先转换为 int。那是因为规范是这么说的。

    因此,+'A'int 类型的表达式。有点奇怪,但是,规范是这样说的。因此,System.out.println(+'A') 打印 65,因为它调用了 printlnint 版本,它只打印 65,而 System.out.println('A'); 调用 char 版本,它打印 'A'

    【讨论】:

    • (+2) -> + 是一元运算符,对吧?和 (+'2') -> 在这里是为了使它强制转换(更改)为 int,对吗?谢谢!在 int 和 char 之间交换有点让我困惑。
    • @elvintaghizade14 我在这个答案中添加了一堆文字来解释 char v int
    • 没有比这更好的解释了。非常感谢!
    【解决方案2】:

    char 是一个数字,所以读作"Apple is " + (+'2') + " USD"

    对于整数的情况也是如此。

    【讨论】:

    • 谢谢!在 int 和 char 之间交换有点让我困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-15
    • 2018-07-22
    • 2018-02-09
    • 1970-01-01
    • 2022-07-11
    • 1970-01-01
    相关资源
    最近更新 更多