Friday, June 28, 2019

Find Largest and Second Largest Number in Given Array - Java Program

This post is about writing a Java program to find the top two numbers (largest and second largest) in a 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.

Solution to find largest and second largest number in an array

Logic here is to have two variables for first and second number and iterate the array. 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.

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.

Largest and second largest number in array Java program

public class FindTopTwo {

 public static void main(String[] args) {
  int numArr[] = {2, 5, 14, 1, 26, 65, 123, 6};
  // Assign lowest possible int value
  int firstNum = Integer.MIN_VALUE;
  int secondNum = Integer.MIN_VALUE;
  for(int i = 0; i < numArr.length; i++){
   if(firstNum < numArr[i]){
    secondNum = firstNum;
    firstNum = numArr[i];
   }else if(secondNum < numArr[i]){
    secondNum = numArr[i];
  System.out.println("Top two numbers : First -  " 
     + firstNum + " Second " + secondNum);


Top two numbers : First -  123 Second 65

That's all for this topic Find Largest and Second Largest Number in Given Array - Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page

Related Topics

  1. How to remove elements from an array - Java Program
  2. Matrix Addition - Java Program
  3. How to Find Common Elements Between Two Arrays - Java Program
  4. Arrange Non-Negative Integers to Form Largest Number - Java Program
  5. How to Remove Duplicate Elements From an Array - Java Program

You may also like-

  1. Count Total Number of Times Each Character Appears in a String - Java Program
  2. Invoking getters and setters using Reflection - Java Program
  3. How to convert date and time between different time-zones in Java
  4. Print odd-even numbers using threads and wait-notify
  5. Insert\Update using NamedParameterJDBCTemplate in Spring framework
  6. How to create immutable class in Java
  7. BigDecimal in Java
  8. interface default methods in Java 8