3

Is int[][] matrix = new int[10][10]; a primitive or is it considered an object? When i send it as a parameter to a function, does it send its reference (like an object) or its value (like a primitive)?

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
AndreiBogdan
  • 10,858
  • 13
  • 58
  • 106

3 Answers3

6

Every Java array is an Object. When you pass it as an argument, you pass a copy of the reference to the array.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • That's what i thought. I wasn't sure because of the int and not Integer in the declaration of the variable. (btw, 11 min till accept :P). Thanks – AndreiBogdan Mar 10 '12 at 08:04
  • 2
    As mentioned, arrays/objects are passed by copy of reference. Specific examples: http://stackoverflow.com/a/333217/879167 – XiaoChuan Yu Mar 10 '12 at 08:07
5

Arrays are objects. Arrays of arrays are also objects. Java doesn't really have multidimensional arrays as such, just support for arrays of arrays.

int [][] foo = {{1}, {2,2}, {3,4,5}};
if (foo instanceof int[][]) { // can only use instanceof with objects
}
System.out.println(foo.getClass()); // has object methods
Adam
  • 35,919
  • 9
  • 100
  • 137
2

In java, arrays are full blown objects. Having said that, all primitives and object references in java are always passed by value and never by reference. In the case of objects, the object reference is passed by value. The difference between this and passing by reference is subtle but significant.

Asaph
  • 159,146
  • 25
  • 197
  • 199
  • Objects aren't passed at all. References are passed, as you say in your third sentence - but your second sentence should be corrected. – Jon Skeet Mar 10 '12 at 08:14
  • @JonSkeet: Thanks. I've changed the second sentence. Is it better now? – Asaph Mar 10 '12 at 08:20
  • this is still quite confusing for someone only learning whats going on and not knowing it. I think you mean that variables that 'are' Objects are actually references, and Java always pass by value.And this value for Objects just happens to be a reference to the "real object". If so, it would help if you add italics to the second sentence too, and maybe clarify that while "object references are passed by value", primitive values are passed by value, too. Also (pun) references citing some language specification about arrays being Objects, and passing/vars, would also raise confidence. – n611x007 Oct 15 '13 at 13:31