Description
In many java interviews especially for freshers, it is asked to write program to find max two numbers from a given array.This kind of program is good to check the programming sense as this program does not use any inbuilt java sorting functions or predefined data structures or collections.It simply uses java iterations and programming sense to swap in between the numbers and find the solution.Following is the implementation.
MaxNumbers.javapackage com.devglan; public class MaxNumbers { public void findTwoMaxNumbers(int[] array){ int maxOne = 0; int maxTwo = 0; for(int num : array){ if(maxOne < num){ maxTwo = maxOne; maxOne =num; } else if(maxTwo < num){ maxTwo = num; } } System.out.println("First Max Number: " + maxOne); System.out.println("Second Max Number: " + maxTwo); } public static void main(String a[]){ int num[] = {6,9,80,56,90,1}; MaxNumbers maxNumber = new MaxNumbers(); maxNumber.findTwoMaxNumbers(num); } }