Java Program to find the smallest number in an Array

To find the smallest element or number in a Java Array, we can utilize the approach of sorting the array in ascending order and returning the element at the first index.

public class SmallestInArrayExample{  
public static int getSmallest(int[] a, int total){  
int temp;  
for (int i = 0; i < total; i++)   
        {  
            for (int j = i + 1; j < total; j++)   
            {  
                if (a[i] > a[j])   
                {  
                    temp = a[i];  
                    a[i] = a[j];  
                    a[j] = temp;  
                }  
            }  
        }  
       return a[0];  
}  
public static void main(String args[]){  
int a[]={1,2,5,6,3,2};  
int b[]={44,66,99,77,33,22,55};  
System.out.println("Smallest: "+getSmallest(a,6));  
System.out.println("Smallest: "+getSmallest(b,7));  
}}

Output:

Java Program to find the smallest number in an Array using Arrays

import java.util.*;  
public class SmallestInArrayExample1{  
public static int getSmallest(int[] a, int total){  
Arrays.sort(a);  
return a[0];  
}  
public static void main(String args[]){  
int a[]={1,2,5,6,3,2};  
int b[]={44,66,99,77,33,22,55};  
System.out.println("Smallest: "+getSmallest(a,6));  
System.out.println("Smallest: "+getSmallest(b,7));  
}}

Output:

Java Program to find the smallest number in an Array using Collections

import java.util.*;  
public class SmallestInArrayExample2{  
public static int getSmallest(Integer[] a, int total){  
List<Integer> list=Arrays.asList(a);  
Collections.sort(list);  
int element=list.get(0);  
return element;  
}  
public static void main(String args[]){  
Integer a[]={1,2,5,6,3,2};  
Integer b[]={44,66,99,77,33,22,55};  
System.out.println("Smallest: "+getSmallest(a,6));  
System.out.println("Smallest: "+getSmallest(b,7));  
}}

Output:

In conclusion, by sorting the Java array in ascending order and returning the element at the first index, we can easily find the smallest number. Follow tutorials.freshersnow.com to learn more.