finding the largest and second largest number in an array in java code example

Example 1: second largest value in array java 8

public class ThirdLargestNumberInAnArray {
   public static void main(String args[]){
      int temp, size;
      int array[] = {10, 20, 25, 63, 96, 57};
      size = array.length;

      for(int i = 0; i<size; i++ ){
         for(int j = i+1; j<size; j++){

            if(array[i]>array[j]){
               temp = array[i];
               array[i] = array[j];
               array[j] = temp;
            }
         }
      }
      System.out.println("Third second largest number is:: "+array[size-2]);
   }
}

Example 2: find the largest and smallest number in an unsorted integer array in Java

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Number of integers to enter:");
    int numberEnter = keyboard.nextInt();
    int numbers[] = new int[numberEnter];
    int pos = 0;
    do {
        System.out.printf("Please enter integer #%d/%d:%n", pos, numberEnter);
        numbers[pos++] = keyboard.nextInt();
    } while (pos < numberEnter && keyboard.hasNextInt());
    int min = numbers[0];
    int max = numbers[0];
    for (pos = 1; pos < numbers.length; pos++) {
        if (numbers[pos] < min) { // <-- test min.
            min = numbers[pos];
        }
        if (numbers[pos] > max) { // <-- test max.
            max = numbers[pos];
        }
    }
    // Display everything.
    System.out.printf("%s Min: %d Max: %d%n", Arrays.toString(numbers),
            min, max);
}

Tags:

Java Example