Traverse an Array in Java - Iterating over Arrays in Java

Traverse an Array in Java - Iterating over Arrays in Java

 

Traverse an Array in Java - Iterating over Arrays in Java

Traversing through an array


Traversing of an array visiting of an 
array is accessing of each element of an array at least once for processing. The array is a linear data structure. Traversing of its elements is very simple and easy.

How do you traverse an array?

Array traversing is done for printing every element, calculating the total number of elements, or execution of any process on these elements

We can use a ‘for’ loop to traverse or visit each element of an array. We can start the index at 0 and loop while an index is less than the length of the array.


public class ArrayTraverseWithForLoop

{

    public static void main(String args[])

    {

        int i;

        int n[]={5,6,7,3,2,4,9,8,10,12}; //Array

        for(i=0; i<n.length; i++)

        {

            System.out.println("Position:"+ i +" " +n[i]);

        }

    }

}

In the above java array traversing program, the array ‘n’ contains elements. Using for loop, each element traverse once and print the elements.

Enhanced for(for-each) Loop to Iterate Java Array

public class ArrayTraverseWithForEachLoop

{

    public static void main(String args[])

    {

        int no[]={5,6,7,3,2,4,9,8,10,12};  // Array

       // for each loop

       for(int x : no)

        {

            System.out.println("Array element " + x) ;

        }

    }

}

Traversing ArrayList elements

import java.util.*; 

class TraverseArrayList

{ 

    public static void main(String args[])

    { 

        //Creating a list of elements 

        ArrayList<Integer> list=new ArrayList<Integer>(); 

        list.add (10); 

        list.add (20); 

        list.add (30);

        list.add (40);

        list.add (50);

        // Visiting each elements using for-each loop 

        for(int no : list){ 

            System.out.println(no); 

        } 

    }  

}

Output

10

20

30

40

50

In the above program, we defined an ArrayList list integer data elements with the add() method. After then we visit or traverse each element with the help of for each loop.

Traversing of an array using while loop in Java

In the following java program, we traverse array with the help of a while loop. In this program, the loop starts with x=0 and iterate till no.length-1 and x++ will do loop iteration.

public class TraverseArrayWithWhile

{

   public static void main(String args[])

    {

        int x=0;

        int no[]={5,6,7,3,2,4,9,8,10,12}; //Array

        // using while loop array traverse

        while(x!=no.length-1)

        {

            System.out.print(no[x] + " ");

            x++;

        }

    }

}


More Tutorial and Programs


Linear Search in  Java - Linear Search

Linear Search in Java - Linear Search

Linear Search in  Java

Linear Search using Java

  • A linear or sequential search is a simple algorithm. 
  • The time complexity of linear search is O (n). 
  • It is very slow as it searches n-1.

In this search algorithm, an array list will be searched one by one from the beginning until the required element is found. If the required element is found in the array then the search is successful otherwise unsuccessful. 

Linear search in java with Numeric data

import java.util.*;

public class LinearSearch

{

    public static void main(String args[])

    {

        Scanner sc=new Scanner(System.in);

        int n[]=new int[10];

        int s, i, f=0;

        System.out.println("Enter 10 number in Array:");

        for(i=0; i<10; i++)

        {

            n[i]=sc.nextInt();

        }

        System.out.println("Enter number to Search:");

        s=sc.nextInt();

        for(i=0; i<10; i++)

        {

            if(n[i]==s)

            {

                f=1;

                break;

            }

        }

        if(f==1)

        {

            System.out.println("Search Successful");

        }

        else

        {

            System.out.println("Search Unsuccessful");

        }

    }

}

Output

Enter 10 number in Array:

30

9

6

4

3

12

44

55

64

3

Enter number to Search:

12

Search Successful

 Linear search in java with String data

 import java.util.*;

public class LinearSearchWithString

{

    public static void main(String args[])

    {

        Scanner sc=new Scanner(System.in);

        String n[]=new String[10];

        String s; // For Search

        int i, f=0;

        System.out.println("Enter 10 number in Array:");

        for(i=0; i<10; i++)

        {

            n[i]=sc.nextLine();

        }

        System.out.println("Enter number to Search:");

        s=sc.nextLine();

        // search the element

        for(i=0; i<10; i++)

        {

            if(n[i].compareTo(s)==0)

            {

                f=1;

                break;

            }

        }

        // if f is 1 then search successful

        if(f==1)

        {

            System.out.println("Search Successful");

        }

        else

        {

            System.out.println("Search Unsuccessful");

        }

    }

}

Output

Enter 10 Name in Array:

Sachin

Tania

Wasim

Yasmin

Kalim

Ummesh

Salim

Dannial

Lalit

Rehan

Enter Name to Search:

Ummesh

Search Successful

Linear search in java with Recursion technique

 public class LinearSearchWithRecursion

{

    // Recursive Method to search

    int linearSearchRecursive (int array[], int init, int length, int search)

    {

        if (length < init)

            return -1;

        if (array[init] == search)

            return init;

        if (array[length] == search)

            return length;

        return linearSearchRecursive(array, init + 1, length-1, search);

    }

    //

    public static void main(String args[])

    {

        int array[] = {4, 6, 7, 8, 9, 5};

        LinearSearchWithRecursion ob = new LinearSearchWithRecursion();

        int search, p ,i;

        search = 9;

        System.out.println("Original Data");

        for(i=0; i<array.length; i++)

        {

            System.out.print(array[i] + " ");

        }

        p = ob.linearSearchRecursive (array,  0,  array.length-1,  search);

        if (p != -1)

           System.out.println("\nSearch successful and " + search  + " is found at " + p);

        else

            System.out.println("\nSearch is unsuccesful " + search + " is not in the array");

    }

}

Output

Original Data

4 6 7 8 9 5

Search successful and 9 is found at 4


More Tutorial and Programs
Getter and Setter in Java - Java Getter and Setter with Example

Getter and Setter in Java - Java Getter and Setter with Example

 

Java Getter and Setter with Example

Getter and Setter in Java

Getter and Setter in java is very important for encapsulation (it is the wrapping of variables and methods into a single unit) data from the outside world. Getter and setter methods are basically used to get and maneuver private variables in a different class.  The getter method retrieves an element of the same name while a Setter sets the element.  Getter and Setter's method is also known as Accessor method.

public class SetterAndGetter 

{ 

    private String name;

    private String idCourse;

    private int age;

 

    public String getName() {

        return name;

    }

   public void setName(String name) 

   {

        this.name = name;

    }

  public String getIdCourse()

  {

        return idCourse;

   }

  public void setIdCourse(String idCourse)

 {

        this.idCourse = idCourse;

    }

 

    public int getAge() {

        return age;

    }

 

    public void setAge(int age) {

        this.age = age;

    }

}

Here private variables are name, idCourse, and age and it cannot be accessed directly from the outside world. In setXXX and getXXX methods facilitate to access the private variables.

Now from another class, those private variables can be accessed very easily

package encapsulation;

public class Encapsulation {

 

    public static void main(String[] args) {

        SetterAndGetter encap=new SetterAndGetter();

        encap.setAge(20);

        encap.setIdCourse("BCA");

        encap.setName("Kamal");

        System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge()+ "Course :"+encap.getIdCourse());

       

    }   

}

In the above example, setter and getter methods are protecting variable’s private String name,

private String idCourse, private int age value from unexpected changes by the outside world or class or from the caller code.

Setter and Getter in java a few important points

  • The hidden variable (private modifier) can be accessed only through a getter and setter that is encapsulated. Encapsulation is wrapping of data into a single unit.
  • The setter/getter methods/ function are used to allot or change and access values of the instance variables of a class.
  • Getters and setters are also known as accessors and mutators, respectively.
  • Encapsulation is associated with getting or setting method.
  • Hiding the internal variable’s property while revealing a property using an alternative representation.
  • Protect a public interface from change. It allows the public interface to remain constant while the execution changes without affecting existing values.

More tutorial and examples of java

Loops in Java - Java loop explained with examples



Java program for Pronic Number