Java Array tutorial with Examples

After seeing many people having doubt about using arrays (in Java) and how they are stored, when are they created etc. i decide to do a post on Arrays in Java, to give my readers a broader and clear view about Arrays declaration, creation and intialization.

Definition, Arrays are complex variablesthat store a group of values under a single variable name.

Declaring Arrays :

An array is imply a sequence of either objects or primitives, all of the same type and is put together under one identifier name. A specific element in an array is accessed by an index or subscript. The index of the array is in a continuous order whereas all array elements are stored at contiguous memory location.

You can declare arrays of any type, either primitive or class :

char[] s;
Point[] p; // Where Point is a class

In Java Programming language, creates a reference to the array that you can use to refer to an array. The actual memory used by the array element is allocated dynamically either by a new statement or by an array initializer.

Creating Arrays :

You can create arrays, like all objects, using the new keyword. 

Ex. for creating an array of primitive (char) type :
s = new char[10];

The above line creates an array of 10 char values. After the creation of the array they are initialized with default values ('\u0000' for characters). To make the array useful you must fill some values in it.


public char[] createArray(){
  char[] s;

  s= new char[26];
  for( int i=0; i<26; i++){
    s[i] = (char) ('A' + i);
  return s;
The above code will generate an array in the heap memory containing Upper Case letters of English Alphabet.

The subscript that indexes the individual array elements always begins from 0and must be maintained in a legal range. Any attempts to extend the specified range otherwise the program will give an ArrayOutofBound Exception.

Creating Reference Arrays :

You can create arrays of objects, using the same syntax as above :

p = new Point[10];

The above line creates an array of 10 references of type Point. However, it doesn't create 10 Point objects.

public Point[] createArray(){
  Point[] p;

  p= new Point[26];
  for( int i=0; i<10; i++){
    p[i] = new Point(i,i+1);
  return p;

The above code generates an array in heap memory with each array element filled with a reference to a Point object.

Initializing Arrays :

When we create an array every element is initialized. In the case, when we created char array all the elements got intialized to ('\u0000') which is null character. 

Note : 

Initializing all variables, including the array elements, is essential from the security point of view of system. Uninitialized elements may hamper your system.

The Java Programming Language allows shorthands that create arrays with initial values:

String str[]={" Code "," 2 "," Learn "};

The above Code is Equivalent to :
String str[];
str = new String[3];
str[0]=" Code ";
str[1]=" 2 ";
str[2]=" Learn ";