0

Can someone please explain in a little detail to me why this code prints 2?

import java.util.*;

public class TestCode2 {
   public static void main(String[] args) {
      int[][] array = {{1,2,3,4}, {5,6,7,8}};
      System.out.println(m1(array)[0]);
     // System.out.println(m2(array)[1]);
   }

   public static int[] m1(int[][] m) {
      int[] result = new int[2];
      result[0] = m.length;
      result[1] = m[0].length;
      return result;
   }
}
2
  • Why are you surprised? Your code is equivalent to printing array.length, which is indeed 2. Commented Oct 21, 2013 at 15:06
  • I'm assuming you're expecting the result to be 8. However, the length of array in main() is two. The two elements inside of it just happen to be arrays of length 4. Commented Oct 21, 2013 at 15:07

3 Answers 3

3
    int[][] array = {{1,2,3,4}, {5,6,7,8}};
=>  int[][] array = {arrayOne, arrayTwo};

The length of array is 2 because it's just a bi-dimensionnal array which contains 2 sub arrays (which have both a length of 4).

So

   array.length = 2;
   array[0].length = length of arrayOne (i.e: length of {1,2,3,4}) = 4
   array[1].length = length of arrayTwo (i.e: length of {5,6,7,8}) = 4


To summarize :

public static int[] m1(int[][] m) {
      int[] result = new int[2];
      result[0] = m.length; //m.length = 2
      result[1] = m[0].length; //m[0].length = length of {1,2,3,4} = 4
      return result; //{2,4}
   }

Then you just print the first element of this array returned, i.e 2.

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

1 Comment

Thank you, I actually just mixed up what m.length and m[0].length meant. Dumb mistake. Just learned about arrays and recursion yesterday
1

This is a 2d array so : when you do like this : int [][] array = {{1,2,3,4},{5,6,7,8}} int a=array.length; \ i.e a=2 this is because the array treats the 2 sets as its element means {1,2,3,4} and {5,6,7,8} are considered as single element sorry for wrong format as i am using mobile

Comments

1

m1() is taking 2D array as i/p & returning a (1D) array with first element as length of the i/p array, which - in this case is 2; Hence 2.

Comments

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.