java没有return语句_Java方法返回类型编译没有return语句

Question 1:

Why does the following code compile without having a return statement?

06000

If a method is declared to have a return type (§8.4.5), then a compile-time error occurs if the body of the method can complete normally (§14.1).

In other words, a method with a return type must return only by using a return statement that provides a value return; the method is not allowed to “drop off the end of its body”. See §14.17 for the precise rules about return statements in a method body.

It is possible for a method to have a return type and yet contain no return statements. Here is one example:

06001

因为编译器知道循环永远不会终止(true总是true,当然),它知道函数不能“正常返回”(离开它的body的末尾),因此没有返回。

Question 2:

On the other hand, why does the following code compile,

06002

even though the following does not.

06003

在0 == 0的情况下,编译器知道循环永远不会终止(0 == 0将永远为真)。但它不知道对于b == b。

为什么不?

Some expressions have a value that can be determined at compile time. These are constant expressions (§15.28).

在你的b == b示例中,因为涉及一个变量,它不是常量表达式,并且没有指定在编译时确定。我们可以看到,在这种情况下总是成立的(虽然如果b是双精度的,如QBrute pointed out,我们很容易被Double.NaN,它是not == itself),但是JLS只规定常数表达式是确定的在编译时,它不允许编译器尝试评估非常量表达式。 bayou.io raised a good point为什么不:如果你开始走下去的道路尝试确定涉及变量的表达式在编译时间,你停止在哪里? b == b是明显的(呃,对于非NaN值),但是b == b a?或(a b)* 2 == a * 2 b * 2?在常量绘制线是有意义的。

因为它不“确定”表达式,编译器不知道循环将永远不会终止,所以它认为该方法可以正常返回 – 它不允许这样做,因为它需要使用return。所以它抱怨缺乏回报。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值