gpt4 book ai didi

java - 最后的行为很奇怪吗?

转载 作者:行者123 更新时间:2023-12-02 07:29:38 24 4
gpt4 key购买 nike

public class Test2 {

public static void main(String[] args) {
Test2 obj=new Test2();
String a=obj.go();

System.out.print(a);
}


public String go() {
String q="hii";
try {
return q;
}
finally {
q="hello";
System.out.println("finally value of q is "+q);
}
}

为什么这个打印是hii从函数go()返回后,finally block 中的值已更改为“hello”?

程序的输出是

finally value of q is hello
hii

最佳答案

这是因为您在finally block 中更改q 的值之前返回了从q 求值的值。您返回了 q,它评估了它的值;然后你改变了finally block 中的q,这并没有影响加载的值;然后使用评估值完成返回。

不要编写这样棘手的代码。如果它让写它的人感到困惑,想象一下它会给下一个人带来什么问题,几年后当你在其他地方时。

关于java - 最后的行为很奇怪吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30265772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com