Java program for finding the second smallest element in an array

Finding second smallest element in array

An array is a group of similar type of data that are addressed by an common name (Arr[]). Array of any type can be created and may have one or more dimensions, i.e. 1-D Array, 2-D Array etc. Here we will learn how to code a java program for finding second smallest element in an array. Lets take an example for better understanding.



  • Step 1 – Initialize a class 
  • Step 2- enter variable
  • Step 3-initialize a for  loop, that with iterate through all the elements
  • Step 4- initialize a if condition for checking the second smallest element. 
  • step 5- store the second smallest element name temp
  • step 6- return that variable to the main method
  • step 7- print the returned value
  • step 8- End

Java code:-

 class prepinsta {  
public static int prep(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[1] ;//2nd element because index starts from 0  
public static void main(String args[]){  
int a[]={7,8,9,5,2};  
System.out.println("Second smallest:  "+prep(a,5));  


Second smallest: 5