Java Program to find the second-largest number in an array.2 min read

Find the second-largest element in an array:

In the below program, we take the user input for How many elements does a user wants in an array and what are the elements with the help of Scanner class. And then declare an integer variable named “Highest” and “secondHighest” which are set to zero.

Now using for loop and if-elseif statement, we check for the highest and the second-highest. That is when the 0th index is greater than the largest, we assigned highest to secondHighest and element at 0th index to highest. But if the 0th index is larger than the secondHighest then we assigned the 0th index element to secondHighest.

The for loop iteration will keep repeating until the length of an array (that is the number of elements). After the end of for loop, we display the result for the highest and second-highest by printing it.

Program for the second-highest element in java with output:

The Output of the second largest element in an array in java:


Also Learn,
Java Interview programs