What is the output of the following code?
public class Test{
public static void main(String args[]){
double[] myList = {1, 5, 5, 5, 5, 1};
double max = myList[0];
int indexOfMax = 0;
for(int i = 1; i < myList.length; i++){
if(myList[i] > max){
max = myList[i];
indexOfMax = i;
}
}
System.out.println(indexOfMax);
}
}
public class Test{
public static void main(String args[]){
double[] myList = {1, 5, 5, 5, 5, 1};
double max = myList[0];
int indexOfMax = 0;
for(int i = 1; i < myList.length; i++){
if(myList[i] > max){
max = myList[i];
indexOfMax = i;
}
}
System.out.println(indexOfMax);
}
}
A. 0
B. 1
C. 2
D. 3
E. 4
Answer: Option B
Solution(By Examveda Team)
In the given program.Line 7 : if(myList[i] > max) execute only on time when i =1;
when i = 1 then myList[i] = 5 and max = 1(so the statement is true and if block will be executed).
Then, max = myList[i] = 5 and indexOfMax = i = 1.
After that if statement always false. so indexOfMax value remain 1.
Therefore the value of indexOfMax is 1 at end of the for loop.
Join The Discussion
Comments ( 1 )
Related Questions on Array
In Java, arrays are objects of which class?
A. Array
B. Collection
C. ArrayList
D. None of the above
How do you declare a one-dimensional array in Java?
A. int[] myArray;
B. int myArray[];
C. Array
D. All of the above
What is the default initial value of numeric elements in an array of type int in Java?
A. 0
B. 1
C. -1
D. Null
What is the correct way to initialize a two-dimensional array in Java?
A. int[][] myArray = {{1, 2}, {3, 4}};
B. int[2][2] myArray = {{1, 2}, {3, 4}};
C. int[2][2] myArray; myArray[0][0] = 1; myArray[0][1] = 2; myArray[1][0] = 3; myArray[1][1] = 4;
D. None of the above
Please explain the answer