Java返回问题

Ric*_*dor 5 java return-value

  1. 不捕获返回值的方法的值有什么影响?

  2. 如果未捕获返回值,是否会产生内存问题等并发症.

示例代码段:

//reference types
public Object[] thismethodreturnsvalue(){
   return new Object[]{new Object(),new Object(),new Object()};
}

//primitive types
public int thismethodreturnsint(){
   return -1;
}

public static void main(String a[]){
   thismethodreturnsvalue();
   thismethodreturnsint();
}
Run Code Online (Sandbox Code Playgroud)

aio*_*obe 3

1、不捕获返回值的方法的值有什么影响?

确实没有什么效果。

将计算返回值,如果它是在堆上创建的(如第一个示例中所示),则它将立即有资格进行垃圾收集。

在第二个示例中,返回值将最终出现在堆栈上,并且在方法返回后将被简单地丢弃。

2. 如果没有捕获返回值,是否会出现内存问题等复杂情况。

不,不是真的。正如我上面所说,它将被垃圾收集。

以下是调用站点发生的情况的字节码转储:

public class Test {

    public static int testMethod() {
        return 5;
    }

    public static void main(String[] args) {
        testMethod();
    }
}
Run Code Online (Sandbox Code Playgroud)

...对应的字节码:

public static int testMethod();
  Code:
   0:   iconst_5
   1:   ireturn


public static void main(java.lang.String[]);
  Code:
   0:   invokestatic    #2;
   3:   pop                 // return value popped immediately.
   4:   return
}
Run Code Online (Sandbox Code Playgroud)