In post of **Find largest and second largest number in the given Array **

Condition here is that you should not be using any inbuilt Java classes or methods (i.e. Arrays.sort) or any data structure.

__Logic to find largest and second largest number in an array__

In this logic we have two variables for first and second number and iterate the array. After that we compare each array element with the first number if first number is less than the array element then assign existing first number to second number and array element to the first number.

**You may also like –**

Find largest and smallest number in the given Array

Find duplicate elements in an Array

Java program to Remove Duplicate Elements From an Array

Core Logic here we have If first number is greater than the array element then check if second element is less than the array element, if yes then assign array element to the second number.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.kkjavatutorials.client; /** * @author KK JavaTutorials * Java Program to find largest and second largest number in the given Array */ public class FindTopTwoLargestNumbersTest { public static void main(String[] args) { int inputNumberArray[] = { 10, 5, 350, 100, 45, 95, 560, 101 }; int firstLargestNum = 0; int secondLargestNum = 0; for (int i = 0; i < inputNumberArray.length; i++) { if (firstLargestNum < inputNumberArray[i]) { secondLargestNum = firstLargestNum; firstLargestNum = inputNumberArray[i]; } else if (secondLargestNum < inputNumberArray[i]) { secondLargestNum = inputNumberArray[i]; } } System.out.println("First Latest Number:" + firstLargestNum+ ", Second Latest Number:" + secondLargestNum); } } |

**Output Of Program:**

1 |
First Latest Number:560, Second Latest Number:350 |

That’s all about this topic **Find largest and second largest number in the given Array**. If you have any doubts or any suggestions to make please drop a comment.

**You May Also Like:**

How to swap two numbers with or without temporary variable in java

Java Program to Swap two numbers using Bitwise XOR Operator?

How to reverse a number in Java

How to check Armstrong number java program

Java program to find factorial of a number

Java Program to Calculate the Power of a Number

Check whether a number is prime or not

Java Program to displaying prime numbers

Fibonacci series using iterative and recursive approach java program

Java program to Remove Duplicate Elements From an Array

Find common elements between two Arrays

Find largest and smallest number in the given Array

Java Program to find duplicate elements in an Array

Count number of words in a string in java

How would you check if a number is even or odd using bit wise operator in Java?

How can you check if the given number is power of 2?

How to check if String is number in java ?

**If you have any feedback or suggestion please feel free to drop in blow comment box.**