JAVA PROGRAM TO FIND THE LAST ELEMENT OF AN ARRAY

JAVA ARRAYS

  • Arrays Iin java are used to represent group of elements as a single entity but these elements are
    of similar types.
  • The size of Array is fixed, it means once we created an array in java, it is not possible to increase and
    decrease it’s size.
  • Array in java is index based, and the first element of the array stored at 0 index.
Advantages of array:-
  • Instead of declaring multiple variables of similar types individually, we can declare group of elements by using array, thereby
    reducing the length of the code and the allowing easier access by just one identifier and indexing for all the elements.
  • We can store the group of objects easily & we are able to retrieve the data easily.
  • We can access the random elements present in the any location based on index.
  • Array is able to hold reference variables of other types.
Different ways to declare a Array:-
  • int[] values;
  • int []values;
  • int values[];
Declaration & Instantiation & Initialization :-

Approach 1:-      int a[]={10,20,30,40};               //declaring, instantiation, intialization
Approach 2:-     int[] a=new int[100];                 //declaring, instantiation

a[0]=10;              //initialization
a[1]=20;
;;;;;;;;;;;;;;;;;;;;;
a[99]=40;

Declares an Array of Integers :-

int[] anArray;

Allocates memory for 10 integers :-

anArray = new int[10];

Initialize first element :-

anArray[0] = 10;

Initialize second element :-

anArray[1] = 20;

and so forth :-

anArray[2] = 30; anArray[3] = 40; anArray[4] = 50; anArray[5] = 60;
anArray[6] = 70; anArray[7] = 80; anArray[8] = 90; anArray[9] = 100;

Example of Arrays in Java :-

An example of arrays in java is there in the code mentioned below :

In this example, we are taking array elements from dynamic input from Scanner class, which is located in the java.util package.

import java.util.Scanner;
class LastElementOfArray {
    public static void main(String arg[]){ 
            Scanner s = new Scanner(System.in);
        System.out.println("Enter the number of elements in the Array");
        int n = s.nextInt();
        int a[] = new int[n];  
        System.out.println("Enter " + n + "array elements : ");  
        for(int i=0;i<n;i++){   
          a[i] = s.nextInt();
            }
  	    System.out.println("Last elment of the array is " + LastElement(a));
    }
    static int LastElement(int a[]){
        if(a.length == 0){
        System.out.println("Array is Empty");
            return 0;
        }
        return a[a.length - 1];	
    }
}

 

Leave a Comment

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

Scroll to Top