Hi there!
I have started learning java just recently and
I found a problem in a programming exercise in which I have to find the second largest number in a given array using programming. I know how to find the largest number,
but I am facing difficulty in making the logic for finding the second-largest number.

Can anybody here help me solve the problem?
Also, provide the example program so that I can understand it better. Thanks!


Hello! The problem you have mentioned is very easy. All you need to do is,
after finding the largest number, apply another logic.

However, consider the following code snippet, which will solve your problem.

Please refer to the comments to better understand the code:

public class Main
public static void main(String[] args) {
int[] arr = {5,3,7,8,2,68,4,19};
int largest = 0, second_largest = 0;
for(int i = 0; i<arr.length; i++)
           //this condition will keep evaluating unless i is less than the length of array or largest number is not found
            if(arr[i] > largest) //if(arr[i] > 0) 
                second_largest = largest; //second_largest = 0
                largest = arr[i]; //assigning the largest element of array to 'largest' variable
            else if(arr[i] > second_largest && arr[i] != largest)//if above condition is false, this will be evaluated in order to find the second largest number

              second_largest = arr[i];
        System.out.println("Largest:" + largest + "\nSecond largest:" + second_largest);


Second largest:19      


I hope you found the answer you were looking for, Thanks!

More Posts

How to find the largest number in an array java? Naymul01 - Oct 24
How to find the largest number in an array c++ ? Naymul01 - Oct 24
Program to find second largest number in an array in java Hafsa_Rao - Jun 19
Program to find maximum and minimum number in an array in java Being human - May 30
Java program to find maximum and minimum number without using array Sanjana Sagar - May 20
Find second largest number in array without sorting in java Mubashir Islam - Oct 23, 2020
How to assign values to array in java using for loop MallikaShaik672 - Nov 4, 2020
How to find the index of an element in an array in Java sakshi - Jul 28
How to sort an array in java without using sort method ? Naymul01 - Oct 26
How to Pass an Array to a Method using Java muliemes - May 18