+ 1

Java Array snippet result- please explain

Can someone please explain why the below code snippet outputs 2? int arr[ ] = new int[3]; for (int i = 0; i < 3; i++) { arr[i] = i; } int res = arr[0] + arr[2]; System.out.println(res);

7th Jul 2020, 1:18 AM
JessP
JessP - avatar
1 Resposta
+ 5
Firstly You had created an int array arr with length 3 then for statement in for firstly i = 0 arr[0]=0 then when i = 1 arr[1]=1 then when i = 2 arr[2]=2 ten when i = 3 i is now not smaller than 3 so loop terminate And Code goes to next Statement which is int res =arr[0]+arr[2] int res = 0 + 2 res= 2 So it is printing 3
7th Jul 2020, 5:09 AM
Akash
Akash - avatar