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)?

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

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
As mentioned, arrays/objects are passed by copy of reference. Specific examples: stackoverflow.com/a/333217/879167
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

Comments

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.

3 Comments

Objects aren't passed at all. References are passed, as you say in your third sentence - but your second sentence should be corrected.
@JonSkeet: Thanks. I've changed the second sentence. Is it better now?
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 <del>(pun) references</del> citing some language specification about arrays being Objects, and passing/vars, would also raise confidence.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.