# How to find largest and smallest number from integer array - Java Solution

Good Understanding of array data structure is very important for any software developer, and to develop this understanding there are lots of programming exercise beginners can do. One of them is writing a program to find smallest and largest number in an integer array. Java programmers are no different than others, so they can do this program in Java, not just to understand array but also relational operators available in Java.  In this program, you need to write a method, yes we call the function a method in Java, which will accept an integer array and then print largest and smallest number from that array. Use of any third-party library or API method is not allowed, which means you need to do this exercise by using basic tools of Java programming language, which includes operators, control statements,  keyword and some classes from java.lang package.

This problem is also known as finding maximum and minimum numbers in an array, and technique mentioned here can be used in any other programming language as well. As a bonus point, you can also write JUnit test cases to test your method, I have not done so and relied on simple main method to test my code to show the output and keep it short, essential for any example or demo.

Btw, if you preparing for programming job interview, then don't forget to check the Cracking the Coding Interview book. It contains 150 Programming Questions and Solutions, which is more than enough for many coding interviews.

## Java Program to find smallest and largest number in an integer array

Here is full code example of Java program to find smallest and largest number from an integer array. You can create a Java source file with name MaximumMinimumArrayDemo.java and copy code there to compile and execute in your favorite IDE. If you don't have IDE setup, you can also compile and run this program by following steps I have shown on HelloWorld in Java.

If you look at the code here, we have created a method called largestAndSmallest(int[] numbers)  to print largest and smallest number from int array passed to the program.  We use two variables largest and smallest to store the maximum and minimum values from the array. Initially largest is initialized with Integer.MIN_VALUE and smallest is initialized with Integer.MAX_VALUE.

In each iteration of the loop, we compare current number with largest and smallest and update them accordingly. Since if a number is larger than largest, it can't be smaller than smallest, which means you don't need to check if the first condition is true, that's why we have used if-else code block, where else part will only execute if the first condition is not true.

Here is another logic to find the largest element from an array in Java, here instead of assigning the variable with Integer.MAX_VALUE, we have assigned the first element from the array.

Since array doesn't override the toString method in Java, we have used Arrays.toString() to print contents of an array. Remember this function is outside of core logic, so it's Ok to use it. Since this is a static method we can directly call this from the main method in Java, and so does our test code. We pass the random array to this method and see if largest and smallest number returned by the method is correct or not. For automated testing, a Unit test is better but for demonstration, you can use the main method.

Java Program to find the largest and smallest element in array:

```import java.util.Arrays;
/**
* Java program to find largest and smallest number from an array in Java.
* You cannot use any library method both from Java and third-party library.
*
* @author http://java67.blogspot.com
*/
public class MaximumMinimumArrayDemo{

public static void main(String args[]) {
largestAndSmallest(new int[]{-20, 34, 21, -87, 92,
Integer.MAX_VALUE});
largestAndSmallest(new int[]{10, Integer.MIN_VALUE, -2});
largestAndSmallest(new int[]{Integer.MAX_VALUE, 40,
Integer.MAX_VALUE});
largestAndSmallest(new int[]{1, -1, 0});
}

public static void largestAndSmallest(int[] numbers) {
int largest = Integer.MIN_VALUE;
int smallest = Integer.MAX_VALUE;
for (int number : numbers) {
if (number > largest) {
largest = number;
} else if (number < smallest) {
smallest = number;
}
}

System.out.println("Given integer array : " + Arrays.toString(numbers));
System.out.println("Largest number in array is : " + largest);
System.out.println("Smallest number in array is : " + smallest);
}
}
Output:
Given integer array : [-20, 34, 21, -87, 92, 2147483647]
Largest number in array is : 2147483647
Smallest number in array is : -87
Given integer array : [10, -2147483648, -2]
Largest number in array is : 10
Smallest number in array is : -2147483648
Given integer array : [2147483647, 40, 2147483647]
Largest number in array is : 2147483647
Smallest number in array is : 40
Given integer array : [1, -1, 0]
Largest number in array is : 1
Smallest number in array is : -1```

That's all about How to find largest and smallest number from integer array in Java. As I said this question can also be asked as to find the maximum and minimum numbers in an Array in Java, so don't get confused there. By the way, there are more ways to do the same task and you can practice it to code solution differently. Can you write a solution which is different than this? go ahead and give it a try.

• How to check if a given number is prime or not? (solution)
• How to find the highest occurring word from a text file in Java? (solution)
• How to find if given String is palindrome in Java? (solution)
• How to reverse an int variable in Java? (solution)
• How do you swap two integers without using the temporary variable? (solution)
• Write a program to check if a number is a power of two or not? (solution)
• How to reverse String in Java without using StringBuffer? (solution)
• How do you reverse word of a sentence in Java? (solution)
• How to find a missing number in a sorted array? (solution)
• How to find the square root of a number in Java? (solution)
• How to calculate GCD of two numbers in Java? (solution)
• How to find duplicate characters from a given String? (solution)

If you are preparing for programming job interview then you must prepare for all-important topic e.g. data structure, string, array etc. One book which can help you on this task is the Cracking the Coding Interview book. It contains 150 Programming Questions and Solutions, which is good enough to clear most of the coding interviews.

1. 2. This code doesn't look right, it should be changed to (remove "else"):
if (number > largest) {
largest = number;
}

if (number < smallest) {
smallest = number;
}

If you try {1, 2, 3}, you will see the difference.

1. Agreed. I ran the code example and encountered the incorrect result. It should be updated to have two separate if statements just as shown above.

2. Why not just set largest/smallest to array instead of INT_MAX, INT_MIN? Then it'll work with the `else`. Setting to INT_MAX/INT_MIN is a rather rookie mistake.

3. Remove "else" because it fails at both places.
1. for largest try ascending order digit (1,2,3)
2. for smallest try descending order digit in negative(-3,-2,-1)

1. Yes, the else looks like a typo, it should be removed otherwise solution will not produce correct result for all outputs.

4. //programm to find largest no in an given array.
public class Larg {

public static void main(String[] args) {
int max=0;
int arr[]={900,2,54,15,40,100,20,011,299,30,499,699,66,77};
max=arr;
for(int i=0;i<arr.length-1;i++)
{
if(max<arr[i+1])
{
max=arr[i+1];
}
}
System.out.println(max);
}
}

5. 6. Can we convert into array into string without API or without Arrays.to String(arr)

7. Can we convert int array to string without using Arrays.to string()

8. private static void largestAndSmallest(int[] numbers) {
int largest = numbers;
int smallest = numbers;

for (int i = 1; i < numbers.length; i++) {
if(numbers[i]>largest){
largest=numbers[i];
}else if(numbers[i]<smallest){
smallest=numbers[i];
}
}

System.out.println("\nGiven integer array : " + Arrays.toString(numbers));
System.out.println("Largest number in array is : " + largest);
System.out.println("Smallest number in array is : " + smallest);
}

9. import java.util.Scanner;

class exam
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);

System.out.println("Enter 5 numbers:");

int[] numbers = new int;
int sum = 0;
int max = numbers;
int min = numbers;

for(int i=0; i<5; i++){
numbers[i] = input.nextInt();
sum = sum + numbers[i];

if (numbers[i] > max){
max = numbers[i];
}
else if (numbers[i] < min){
min = numbers[i];
}

}

int average = sum / 5;

System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
System.out.println("Max: " + max);
System.out.println("Min: " + min );
System.out.println("Display sorted data : " + numbers );
}
}

How come the min is always displaying 0...Please can someone help me...Thanks in advance

1. Else in this snippet "else if (numbers[i] < min){" is the culprit

10. public void doAlgorithm(int a[]){
int big = 0, temp = 0;
for (int i = 0; i < a.length; i++) {
for (int j = i+1; j < a.length; j++) {
big = (a[i] > a[j]) ? a[i] : a[j];
if(temp < big)
temp = big;
}
}
System.out.println(temp);
}

11. laughable

why all this hassle with Integer.MAX_VALUE and Integer.MIN_VALUE?
Simply make your largest and smallest values equal to the numbers. Then you can save one iteration.

What if the numbers is empty? You will still get Integer.MIN_VALUE and Integer.MAX_VALUE which obviously would be incorrect. You need to check for empty and null array.
A programmer should learn to check his inputs way earlier, than he would learn algorithms. It's a matter of simple hygiene - learn to brush your teeth before learning how to assemble fusion reactor.

12. int[] arr = {1,3,2,6,3};
Arrays.sort(arr);
int min = arr;
int max = arr[arr.length-1];
System.out.println(min + ":" + max);

13. Here is the code

14. Why not you correct code in this post..please replace else if with if condition..

15. int a[]= {10,3,0,1,45,22,667,8,99,0,3};
int min = a;
int max = a;
int minPos = 0;
int maxPos = 1;
if(maxa[i]) {
min = a[i];
minPos = i;
}
if(max<a[i]) {
max = a[i];
maxPos = i;
}

}
System.out.println("min : "+ min +" Pos : "+(minPos+1));
System.out.println("max : "+ max +" Pos : "+(maxPos+1));

16. import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.apache.commons.lang3.ArrayUtils;

public class Test{

int []arr = {-1 , 3,2, -9, 5 ,6 ,-4};
System.out.println("Largest is "+findLargest(arr));
System.out.println("Smallest is "+findSmallest(arr));
}
private static int findSmallest(int[] arr) {
List b = Arrays.asList(ArrayUtils.toObject(arr));

return (int) Collections.min(b);
}
public static int findLargest(int [] arr){
List b = Arrays.asList(ArrayUtils.toObject(arr));

return (int) Collections.max(b);
}
}

17. public static void main (String []args){

largestAndSmallest(new Integer[]{-20, 34, 21, -87, 92,
10,100,-120});

}
public static void largestAndSmallest(Integer[] numbers)
{
int largest = 0;
int smallest = 0;
int temp = 0;

/*
//// simple using builtin function for sorting array in ascending order ////
Arrays.sort(numbers);
System.out.println("In asscending order : " + Arrays.toString(numbers));

//// simple using builtin function for sorting array in descending order ////
Arrays.sort(numbers, Collections.reverseOrder());
System.out.println("In descending order : " + Arrays.toString(numbers));

*/

for(int i=0; i numbers[j]){
// temp = numbers[i];
// numbers[i]=numbers[j];
// numbers[j]=temp;
// }
// largest = numbers;
// smallest = numbers[j];
}
}

System.out.println("Given integer array : " + Arrays.toString(numbers));
System.out.println("Largest number in array is : " + largest);
System.out.println("Smallest number in array is : " + smallest);

}

18. import java.util.BitSet;

public class SmallestLargest {
public static void main(String[] args) {
int array[] = new int[] {4,64,3,67,12};
BitSet bitSet = new BitSet();
for(int i = 0; i < array.length; i++) {
bitSet.set(array[i] - 1);
}
System.out.println("Smallest Number is " + (bitSet.nextSetBit(0) + 1));
System.out.println("Largest Number is: " + bitSet.length());
}
}

19. you can just replace the max and the min with the first element and it works.
just use arr in both places

20. public class FindMaxSmall {

public static void main(String[] args) {
// TODO Auto-generated method stub

int[] arrayValue = { 2, 3, 1, 4, 7, 8, 5, -1, -2, 99, 2, 2, 99 };

int maximum = arrayValue;
int minimum = arrayValue;

for (int i=1;i maximum) {
maximum = arrayValue[i];
}

if (arrayValue[i] < minimum) {

minimum = arrayValue[i];
}
}

System.out.println("Maximum Value" + maximum);

System.out.println("Minimum Value" + minimum);

}

}

21. public class MyClass {
public static void main(String args[]) {
int[] array = {2,1,3,4,5,6,7,8,10,9};

int min=array;
int max=0;
for(int i=0;iarray[i])
{
min=array[i];
}else if(max<array[i]){
max=array[i];
}

}
System.out.println("Min Number = " + min);
System.out.println("Max Number = " + max);

}
}

1. Ware is your if condition??