Java return problem

  • What is the effect of not capturing the value of the method returning the value?

  • It has difficulties, such as memory problems, if the return value was not found.

Examples of code snippets:

//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();
}
+5
source share
6 answers

1. What is the effect of not capturing the value of a method that returns a value?

The effect really doesn't work.

The return value will be calculated, and if it was created on the heap (as in the first example), it will immediately have the right to garbage collection.

In your second example, the return value will end on the stack and will simply be discarded after the method returns.

2. , , .

, . , .

, :

public class Test {

    public static int testMethod() {
        return 5;
    }

    public static void main(String[] args) {
        testMethod();
    }
}

... -:

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
}
+3
  • . , , , , - .

  • . .

+2

, . API (, String.replace()).

+1

, ,

0

, , .

, : , .

, , . . . , .

, , - , () .

- , . , . , , " ". .

0

JVM . , , , .

, - , , - , .

-1

All Articles