Count the total number of elements in an array in Java

Hello geeks, In this blog, we will be going to learn how we can count the total number of elements in an array in Java.

Algorithm of Program:

  • STEP 1: START
  • STEP 2: INITIALIZE arr = {5,4,3,6,2}
  • STEP 3: Sort the Array
  • STEP 4: PRINT arr. length

For Sorting We are using Arrays. sort() it is a method residing in Arrays class.

  • Program 1: If Arrays are not sorted:

public class CountElement {

  public static void main(String[] args) {
  
                    int [] array = {5,4,3,2,1};  
                    Arrays.sort(array);
        
          System.out.println("Number of elements present in given array: " + array.length);  
      }  
  } 

Output:

Number of elements present in given array: 5
  • Program 2: If Arrays are Sorted:

public class CountElement { 
public static void main(String[] args) {\

 int [] array = {1,2,3,4,5};

 System.out.println("Number of elements present in given array: " + array.length);
 }
 }

Output:

Number of elements present in given array: 5

Leave a Reply

Your email address will not be published. Required fields are marked *