How the output is coming 10 and 40? Please explain. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How the output is coming 10 and 40? Please explain.

public class Test { public static void methodOne(int[]... x) { for(int[] a:x) { System.out.println(a[0]); } } public static void main(String[] args) { int[] l={10,20,30}; int[] m={40,50}; methodOne(l,m); } } // Output - 10 40

27th Jan 2022, 2:06 AM
Minhaj Haider
Minhaj Haider - avatar
4 Answers
+ 2
The use of the variadic parameter (...) will result in the arguments being placed into an array like structure themselves. So, when the arrays l and m are passed you end up with a 2d array like; {{10,20,30}, {40,50}} Then the loop will loop through each of the nested arrays and output the element in the 0th position. Hence, 10 and 40.
27th Jan 2022, 2:17 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
ChaoticDawg , it'll 2d array.... What if, I'll give more like int[] x={3,4,5,6} int[] x={1,6,3,7,3} int[] x={56,76,1,7,9} Then, it'll return all arrays 0th index value?
27th Jan 2022, 2:22 AM
Minhaj Haider
Minhaj Haider - avatar
+ 1
Minhaj Haider(MiDer) Yes, it should, try it and see
27th Jan 2022, 2:31 AM
ChaoticDawg
ChaoticDawg - avatar
+ 1
ChaoticDawg okay thanks 😊
27th Jan 2022, 9:15 AM
Minhaj Haider
Minhaj Haider - avatar