How to get the first and last item in an array in Java? Example Tutorial

Firstly, before going about finding the first and the last item of an array in java. We need to fully understand what an array is and how it works. What then is an Array? An array is a data structure in java that holds values of the same type with its length specified right from creation time. Think of a container, like a crate of eggs or coke. What I am trying to say is that when you are creating your array, the items coming in must be the same as you have specified as length and you must specify how many items are coming. If you have stated that the items coming are integers, so it is and no other data type (e.g string, char e.t.c) can be there and vice versa. Or you can say an array is a collection of similar type of elements which has contiguous memory location.


Oftentimes you may have to work on a task whereby you will have to store a large number of values during the execution of a program. for instance, you need to read 50 numbers, calculate their average, and find out how many numbers are above the average, and how many numbers are below average.

Your program first reads the numbers and calculates their average, then compares each number with the average to determine whether it is above the average or below. To accomplish this task, the numbers must all be stored in variables.

You have to declare 50 variables and repeatedly write almost identical code 50 times. Writing a program this way would be impractical.



How to get the first and last item in an array in Java?

So, how do you solve this problem? An efficient, organized approach is needed. Java and most other high-level languages provide a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. In the present case, you can store all 50 numbers into an array and access them through a single array variable.


Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array. 


In Java, an array is an object of a dynamically generated class. Java array inherits the Object class and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java

How do you create an array?


  1. Int [] num = new int [5];

In these previous lines of codes, you are creating an array of integer numbers with the variable name "num" and you are assigning it to a new integer of length 5. meaning that the items coming can only be an integer and it has to be 5. anything that does not correlate with what you have specified results to compilation error.

In an array you can access each element through its index, the index number starts from zero. So the first element is index num 0, the second element is index num 1, and the third element is index num 2, and on and on as you can see above.

If you want to get the total number of the index you will do length - 1 because the length you specified at creation time is 5 and because the indexes start from 0, not 1. so, the length of the indexes is 4.

 

There are two types of array.

  • Single Dimensional Array
  • Multidimensional Array



you can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.

 

Note:

 Array indexing always starts with zero, Not 1. Please don’t forget.

 Array knows its length.




Array Methods in java.

An Array is a class in java or it is pretty to say an object a reference type by nature that can hold either primitive types of values or reference types. There are methods readily available in java arrays that you can call to use at any time:
  • Arrays.toString() : This method prints an array
  • Arrays.asList(): This method takes an array and converts it to list
  • Arrays.sort(): This method sorts an array.
  • Arrays.compare(): This method compares two different arrays.
  • Arrays.fill(): This method populates an empty array with the items you put in the method.
  • Arrays.equals(): This method checks if two arrays are equal.
  • Arrays.copyOf(): This method makes another copy of the same array you use this method on.

E.t.c.


How to get the first and last item in an array in Java? Example Tutorial



Let’s check a few lines of codes, we want to find the first and the last element in an array!

 

  1. public class Code{
  2. public static void main(String args[]){
  3. int a[]=new int[5];
  4. a={1,2,3,4,5};
  5. int size=a.length;
  6. System.out.println("First element of an array is" +a[0]);
  7. System.out.println("Last element of an array is "+a[size-1]);
  8. }
  9. }


Line 1 is a class declaration. And 3 is the main method. An array was created in line 5 with values initialized to them at creation. The array’s length method was called and stored inside variable size, line 8 prints the first element, and line 9 prints the last element.

OUTPUT:
The first element of an array is 1

The last element of an array is 5


That's all about how to find the first and last element of an array in Java. You can use this technique to solve many coding problems as this is very basic and every programmer must know about it. 

By the way, If you like this coding problem and are interested for more such problems check out these interesting problems and articles :
  • How do find the largest and smallest number in an array? (solution)
  • How to find prime factors of an integer in Java? (solution)
  • How to check if LinkedList contains any cycle in Java? (solution)
  • Write a Program to remove duplicates from the array without using Collection API? (program)
  • Write a program to check if a number is Prime or not? (solution)
  • Write a method to count occurrences of  a character in String? (Solution)
  • How to find a Fibonacci sequence upto a given Number? (solution)
  • How to check if a number is Armstrong number or not? (solution)
  • Write a method to remove duplicates from ArrayList in Java? (Solution)
  • Write a program to check if a number is Palindrome or not? (program)
  • Write a program to check if Array contains duplicate number or not? (Solution)
  • How to calculate Sum of Digits of a number in Java? (Solution)
  • How to prevent Deadlock in Java? (solution)
  • How to reverse String in Java without using API methods? (Solution)
  • Write a method to check if two String are Anagram of each other? (method)
  • Write a function to find the middle element of linked list in one pass? (solution)
  • How to solve Producer-Consumer Problem in Java. (solution)
  • Write a program to find first non repeated characters from String in Java? (program)
  • How to check if a number is binary in Java? (answer)
  • Write a Program to Check if a number is Power of Two or not? (program)
  • How to find a largest prime factor of a number in Java? (solution)
  • How to calculate factorial using recursion in Java? (algorithm)
  • How to declare and initialize two dimensional array in Java? (solution)
  • Write a program to find missing number in a sorted array? (algorithm)
  • How to search element in array in Java? (solution)
  • 10 Points about Array in Java? (must know facts)
  • How to find top two maximum on integer array in Java? (solution)
  • How to sort array using bubble sort algorithm? (algorithm)
Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question or doubt then please let us know and I'll try to find an answer for you.
  

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.