4
int x[][] = {{1, 2}, {3, 4}};

Since arrays are objects and 2-dimensional arrays are arrays of arrays, then how many objects are in this little piece of code?

4
  • How many are they in your opinion and why do you think like that ? Commented Apr 3, 2013 at 10:14
  • I want to say either 2 or 3, but I wasn't sure if maybe the whole thing could be considered 1 object. Commented Apr 3, 2013 at 10:14
  • Refer here stackoverflow.com/questions/5892905/… Commented Apr 3, 2013 at 10:16
  • @Joe2013 - This question is substantially different to that one. This one is about multi-dimensional arrays. Commented Apr 3, 2013 at 12:20

2 Answers 2

10

Three. One for the top level array of int[] objects, and two int[] objects.

The elements (the integers themselves) are not objects.


My criterion for being "an object" is something that has java.lang.Object as a direct or indirect supertype. All array types are implicitly subtypes of Object, but int is a primitive data type ... and not a subtype of Object.

The other thing to note is that int[][] means "array of int[]" ... in a very literal sense. The int[] objects that you find in an int[][] are real, first-class objects. Your declaration

    int[][] x = {{1,2}, {3,4}};

is a short-hand for this:

    int[][] x = new int[2][]();
    x[0] = new int[]{1, 2};
    x[1] = new int[]{3, 4};
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. I was leaning towards 3, but I wanted to be sure. And thanks for not being condescending or giving my question a negative vote. I read an entire chapter on arrays and googled for an answer to this question and since it was not explicitly stated anywhere I resorted to stackoverflow. I didn't think it was a dumb question, but some people gave it negative votes.
And of course x[0] = new int[]{1, 2}; (which you seem to have typoed as )) is itself shorthand.
@Neil - Thanks. Right on both counts. However, I don't need to drill down through the 2nd level of short-hand to make the point I am trying to make.
Indeed, you only needed to show all of the objects.
0

You can adopt three point of views:

  • There are four int values in your 2-dimentional array.
  • You can also see a single 1-dimentional array containing two 1-dimentional arrays, each containing two values.
  • A third point of view, centered on int vs arrays is exposed by Stephen C in his answer, which makes three arrays and four int values and is actually the second-one rephrased differently (so 3 POVs)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.