Examveda
Examveda

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);
        }
}

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.

This Question Belongs to Java Program >> Array

Join The Discussion

Comments ( 1 )

  1. Ranjan Deb
    Ranjan Deb :
    7 years ago

    Please explain the answer

Related Questions on Array