Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java return Issue

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

  2. Does it develop complications like memory issues if the return value was not caught.

Example 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();
}
like image 300
Richeve Bebedor Avatar asked Feb 24 '11 22:02

Richeve Bebedor


People also ask

Why is my return statement not working?

You need to return something in the case that return fill; is never executed. That can happen if height or width is less than 1 . In this case, it doesn't make sense to enter a for loop (or even 2 loops) if all you're going to do is return fill .

How does return work in Java?

What is a return statement in Java? In Java programming, the return statement is used for returning a value when the execution of the block is completed. The return statement inside a loop will cause the loop to break and further statements will be ignored by the compiler.

What is missing return in Java?

The “missing return statement” message occurs when a method does not have a return statement. Each method that returns a value (a non-void type) must have a statement that literally returns that value so it can be called outside the method.

What is returned by == in Java?

length . == is an operator which returns true when its left and right side are equal and false otherwise.


1 Answers

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

No effect really.

The return value will be computed, and if it was created on the heap (as in your first example), it will be eligible for garbage collection right away.

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

2. Does it develop complications like memory issues if the return value was not caught.

No, not really. As I said above, it will be garbage collected.

Here is a bytecode dump of what happens at the call site:

public class Test {

    public static int testMethod() {
        return 5;
    }

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

... corresponding bytecode:

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
}
like image 181
aioobe Avatar answered Sep 28 '22 05:09

aioobe