-1

Does not storing or using what "sum" returns potentially cause a memory leak?

public int sum(int a, int b){
    System.out.println("total is: "+(a+b));
    return a+b;
}

sum(2,3);
Nelson Matias
  • 453
  • 1
  • 4
  • 15
  • No. The return value will not be stored in any variable. Hence, no memory is allocated for it. – Aziz Jan 02 '19 at 20:05
  • You could clarify a bit, why are you asking this? Java has garbage collection, so only way to leak memory is to leave static (or otherwise long-lived) variables (often in containers) pointing to allocated objects, so they can't be freed even though they are not used ever again. – hyde Jan 02 '19 at 20:07
  • Further, this function returns primitive type, which won't have any allocation which needs to be freed. What kind of memory leak are you worried about? – hyde Jan 02 '19 at 20:08

2 Answers2

4

No, it does not. As it is a primitive value, it lives on the stack, and no heap memory is allocated for it.

But let's suppose, for the sake of demonstration, you are returning an object and not a primitive value (ex. return new Integer(a+b)). There would still be no memory leak, as the object being returned would have no references to it, and thus would be subject to garbage collection.

Joe C
  • 15,324
  • 8
  • 38
  • 50
  • Thank you for the answer. Going by your second part, if I were to return an Int Object, as in "return new Integer(a+b);" and store the result as "Integer res = sum(2,3);" and never use "res". Would this be subject to memory leaks? – Nelson Matias Jan 02 '19 at 20:28
  • 1
    If `res` is never used, then it will become subject to garbage collection when it goes out of scope. – Joe C Jan 02 '19 at 20:30
  • what will happen to the return if i simply use "sum(2,4)" ? – Nadhas Aug 19 '19 at 06:21
-1

No, Java has the garbage collector to help manage the memory. Hope this could help. What is the garbage collector in Java?