Java program to search an element in an array

Posted By: Java Examples - 8:40 AM

Share

& Comment


Search an element in an array

Find an element from an array using Linear Searching. Linear searching is a good way to find an element from the array. The array can be of any order, it checks whether a certain element (number , string , etc. ) is in a specified array or not. Basically it is used for small arrays. In the given code, we have allowed the user to enter the numbers to be stored into the arrays. If the element is found we can return the index where the element is located in the array. If the element is not found we can return -1.  



Java version of this program is given bellow :
       
public class Search_Ele {
public static void main(String[] args){
       int[] array={11,-10,25,18,45,55,30,87,-28,18};

       System.out.println("The contents of the Array are :");

       for(int i=0;i<array.length;i++)
          System.out.println("Array[" + i + "] = " + array[i]);

       int search_element=55;
       int find_index=-1;

       for(int j=0;j<(array.length-1);j++){
          if(array[j]==search_element){
             find_index=j;
             break;
          }
       }

       if(find_index!=-1){
          System.out.println(" The search element is : " + search_element);
          System.out.println(" It is found in the array at position : " + find_index);
       }

       else
          System.out.println("\n The search element is not found in the array.");
    }
 }

About Java Examples

I’m passionate about Web Development and Programming and I go to extreme efforts to meet my passion. I’m a believer of learning the fundamentals first. I try to understand everything little bit more than the average.

Copyright © 2016 Java Examples ACHCHUTHAN.ORG. Designed by Templateism .