Java arrays Tutorial with Examples

10 Flares Twitter 0 Facebook 3 Google+ 7 Pin It Share 0 LinkedIn 0 Filament.io 10 Flares ×

The array data structure in Java is similar to the array structure in other languages like C++. The array stores sequential  collection of elements of the same type. Typically you declare the type of the array and then store the elements of that type in the array. Arrays are stored with an index. That means you can access elements of an array using its index in the array. The elements are stored sequentially in the array.

Array Declaration

There are two ways in which you can declare an array in Java.

In the first option, you declare the type first ( indicate it as an array type using [] ) and then the variable.

In the second approach you declare the variable as array and then define its data type

I prefer the first approach as it is more clearer declaring that this is an array of  so and so type. For example, int [] ids is more clearer than saying int ids[]

Array Creation

An array can be created using the new operator.

Note that you need to specify the size of an array up-front. The above statement creates an array of the specified size. You can only add the declared type to the array or the compiler will throw an exception.

A short hand notation for declaring arrays is as follows

This short hand notation works because the compiler can easily find out the size of the array by inspecting the values in the brackets (  {} )

Array Example

You can also use the short hand notation and declare it as

Following picture represents array a. Please note that the array index starts at zero (0).

arrays in java
arrays in java

Accessing arrays

Arrays can be accessed using its index. If we want to access and element at a particular index , it can be done as below

To access all elements of an array we can use a normal for loop or from JDK 1.5 onwards, an enhanced for loop

 

Arrays Class

The java.util.Arrays class contains various static methods for sorting and searching arrays, comparing arrays, and filling array elements. These methods are overloaded for all primitive types.

public static void sort(Object[] a)

Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. Same method could be used by all other primitive data types ( Byte, short, Int, etc.)

static void fill(int[] a, int val)
Assigns the specified int value to each element of the specified array of ints.

Java.util.Arrays Class

  • Edimara

    Very good!

  • Rajesh

    Simple and good