为什么变量初始化为赋值表达式[String x =(x = y)]编译? [英] Why does variable initialization of to an assignment expression [String x = (x = y)] compile?

查看:101
本文介绍了为什么变量初始化为赋值表达式[String x =(x = y)]编译?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何编译没有错误?根据我的理解,编译器会检查变量的类型(在本例中为 String ),然后查看右侧表达式的类型是否与变量的类型相对应(或至少是一个子类型,但让我们坚持使用 String 类的简单情况,因为它是最终的)。

How does this compiles without error? As my understanding, the compiler checks the type of the variable (in this case String), then sees if the type of the expression on the right side corresponds to the variable's type (or at least a subtype but let's stick to the simple case with the String class since it's final).

public class InitClass {
  public static void main(String[] args) {
    String str = (str = "hello");
    System.out.println(str);
  }
}

我的问题是如何 str =hello编译?编译器是否已经知道 str 的类型应为 String

My question is how does str = "hello" compile? Is the compiler already aware that str should be of type String?

推荐答案

在评估赋值表达式


首先,计算左侧操作数以生成变量。 如果
此评估突然完成,则分配表达式
突然完成,原因相同;右手操作数不是
评估,也不会发生任何分配。

First, the left-hand operand is evaluated to produce a variable. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason; the right-hand operand is not evaluated and no assignment occurs.

产生变量 STR 。那么


否则,评估右手操作数。如果此评估
突然完成,则赋值表达式突然完成
,原因相同,并且没有赋值。

Otherwise, the right-hand operand is evaluated. If this evaluation completes abruptly, then the assignment expression completes abruptly for the same reason and no assignment occurs.

在您的示例中,右侧操作数本身是另一个赋值表达式。所以 str ,再次评估赋值运算符的右手操作数,以产生一个变量 str 。然后

In your example, the right hand operand is itself another assignment expression. So str, the right hand operand of the assignment operator, is again evaluated to produce a variable, str. Then


否则,右手操作数的值转换为左手变量的
类型,是受到价值集转换
(§5.1.13)到适当的标准值集(不是
扩展指数值集),,转换结果是
存储进入变量。

所以存储了hello进入 str 以来

So "hello" is stored into str. And since


在运行时,赋值表达式的结果是赋值发生后变量的
的值。
赋值表达式的结果本身不是变量。

At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.

分配你好到 str 是值hello,该值再次出现存储在 str

the result of the assignment of "hello" to str is the value "hello", that value is again stored in str.

这篇关于为什么变量初始化为赋值表达式[String x =(x = y)]编译?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆