Can somebody clarify the below java code?

Just declare the variable ‘var’ out of the for loop and you will get the desired output.
You are getting that unexpected output because each time, var was getting element from array it was getting initialised to 1.
The variable var for each iteration takes elements from array i.e during iteartion-1 it takes 1 then 2 and so on, the array’s starting location is 0 and the value at that location is 1 hence var will contain 1 during first iteration. Both are same.

Leave a Comment