Arrays in Java
An array in Java is a group of like-typed variables
referred to by a common name. Arrays in Java work
differently than they do in C/C++. Following are
some important points about Java arrays.
• Since arrays are objects in Java, we can find their
length using the object property length. This is
different from C/C++, where we find length using
sizeof.
• The variables in the array are ordered, and each
has an index beginning from 0.
• Java array can be also be used as a static field, a
local variable, or a method parameter.
• An array can contain primitives (int, char, etc.) and
object (or non-primitive) references of a class
depending on the definition of the array.
• In the case of primitive data types, the actual values
are stored in contiguous memory locations.
• In the case of class objects, the actual objects are
stored in a heap segment.
Creating, Initializing, and Accessing an Array
The general form of a one-dimensional array
declaration is
type var-name[];
OR
type[] var-name;
• An array declaration has two components: the type and the name.
type declares the element type of the array.
• Like an array of integers, we can also create an array of other
primitive data types like char, float, double, etc., or user-defined data
Example:
// both are valid declarations
int intArray[];
or
int[] intArray;
• Although the first declaration establishes that
intArray is an array variable, no actual array exists.
• It merely tells the compiler that this variable
(intArray) 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.
var-name = new type [size];
• Here, type specifies the type of data being allocated,
• size determines the number of elements in the array, and
• var-name is the name of the array variable that is linked to
the array.
int intArray[]; //declaring array
intArray = new int[20]; // allocating
memory to array
Combine both declaration and Instantiation
int[] intArray = new int[20]; // combining
both statements in one
• The elements in the array allocated by new will
automatically be initialized to zero (for numeric
types), false (for boolean), or null (for reference types)
In a situation where the size of the array and
variables of the array are already known, array
literals can be used.
int[] intArray = new int[]
{ 1,2,3,4,5,6,7,8,9,10 };
Accessing Java Array Elements using for Loop
• Each element in the array is accessed via its index.
• The index begins with 0 and ends at (total array
size)-1.
// accessing the elements of the specified
array
for (int i = 0; i < [Link]; i++)
[Link]("Element at index " + i + "
: "+ arr[i]);
Multidimensional Arrays
• Multidimensional arrays are arrays of arrays
• A multidimensional array is created by
appending one set of square brackets ([]) per
dimension.
Examples:
int[][] intArray = new int[10][20]; //a 2D
array or matrix
int[][][] intArray = new int[10][20][10]; //a