Arrays in Java

Arrays

An array is a group of like-typed variables that are referred to by a common name.Arrays in Java work differently than they do in C/C++. Following are some important point about Java arrays.

  • In Java all arrays are dynamically allocated.(discussed below)
  • Since arrays are objects in Java, we can find their length using member length. This is different from C/C++ where we find length using sizeof.
  • A Java array variable can also be declared like other variables with [] after the data type.
  • The variables in the array are ordered and each have an index beginning from 0.
  • Java array can be also be used as a static field, a local variable or a method parameter.
  • The size of an array must be specified by an int value and not long or short.
  • The direct superclass of an array type is Object.
  • Every array type implements the interfaces Cloneable and java.io.Serializable.
One-Dimensional Arrays :
type var-name[];
OR
type[] var-name;

Although the above first declaration establishes the fact that intArray is an array variable, no array actually exists. It simply tells to the compiler that this(intArray) variable will hold an array of the integer type. To link intArray with an actual, physical array of integers, you must allocate one using new and assign it to intArray.

Instantiating an Array in Java

When an array is declared, only a reference of array is created. To actually create or give memory to array, you create an array like this:The general form of new as it applies to one-dimensional arrays appears as follows:

var-name = new type [size];

Multidimensional Arrays

int[][] intArray = new int[10][20]; //a 2D array or matrix
int[][][] intArray = new int[10][20][10]; //a 3D array

From GeeksforGeeks

Check Arrays source code in Java

Leave a Reply