Reputation: 83
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;
}
}
Upvotes: 0
Views: 67
Reputation: 1552
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.
Upvotes: 1
Reputation: 93842
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
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.
Upvotes: 3
Reputation: 419
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
Upvotes: 1