4

Possible Duplicate:
Is Java “pass-by-reference”?

if we have big byte[] array (like 40Mb) and we want to send it in method

method(array);

will the array be copied? So memory will increase by another 40Mb in Java env => 80Mb, right?

If yes, how can we destroy the 'first' array after calling the method?

Community
  • 1
  • 1
VextoR
  • 5,087
  • 22
  • 74
  • 109
  • See also http://stackoverflow.com/questions/15871825/why-is-an-arraylist-parameter-modified-but-not-a-string-parameter – Raedwald Apr 30 '14 at 07:39

5 Answers5

7

No, the array will not be copied.

In Java, everything is always passed by value.

Variables of non-primitive types are references to objects. An array is an object, and a variable of an array type is a reference to that array object.

When you call a method that takes a non-primitive type parameter, the reference is passed by value - that means, the reference itself is copied, but not the object it refers to.

Jesper
  • 202,709
  • 46
  • 318
  • 350
1

No new Object will be created, Just a reference will be copied to function parameter.

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
1

The variable array is actually just a reference to the array object. When you pass array to a function you are just copying the reference not the actual array the the reference refers.

codaddict
  • 445,704
  • 82
  • 492
  • 529
1

Java is always pass by value. The value being passed is the value of the variable in the case of a primitive type and the value of the reference held by a variable in the case of an Object.

In this case, an array is an Object and what is passed by value is the reference to that Object. So no, the array will not be copied.

assylias
  • 321,522
  • 82
  • 660
  • 783
0

No, the array will not be copied. In fact, because:

  1. In Java, everything is always passed by value.

  2. Array itself is a object.

So, the result is array' will be copy for method, but the thing it contains: bytes elements DOES NOT copy. so, everything you change for array in the method will affect the original array.

So, memory will not double as you see :)

hqt
  • 29,632
  • 51
  • 171
  • 250