Java 在中更改的值最终在try块中被忽略

Java 在中更改的值最终在try块中被忽略,java,Java,在下面的代码段中,将忽略finally块中更改为20的j值,并返回原始值10 public class Test{ public static void main(String args[]){ int i=testMethod(10); System.out.println(i); } public static int testMethod(int j){ try{ return j;

在下面的代码段中,将忽略finally块中更改为20的j值,并返回原始值10

public class Test{

    public static void main(String args[]){
        int i=testMethod(10);
        System.out.println(i);
    }

    public static int testMethod(int j){
        try{
            return j;
        }finally{
            j=20;
        }
    }
}

finally在整个try块完成后执行。这意味着,在本例中,j已经被读取,即将返回。j在finally块中赋值后不会被重新读取,因此,赋值没有明显的效果。

如果要将j返回为20,则将return语句放在finally块之后,而不是try块中。那么,如果将j=20替换为return 20,会发生什么情况呢?@lagerber 20将在这种情况下返回。因此,finally块内的任何类型的赋值操作基本上都是冗余的它?@amardepbhowmick,除非它是一个全局变量,或者您稍后在finally块中读取该变量。