Java Array

Array Introduction

Array in java is treated as object.


Array can store multiple variables of homogeneous type. It means you can store many variables to array that holds data of similar type.

Types of value stored

Array can be used in java to hold:

  • Primitive values, or
  • Objects

No matter which kind of value array holds it will be stored on heap as object.

When you decide to use an array, you need to first

  1. Declare an array, then
  2. Construct array object, and finally
  3. Populate the array

We will learn about each of them in this java tutorial step by step in detail.


Types of Array

Array can be used in two forms:

  1. Single dimensional array
  2. Multi-dimensional array

Declare Array

Single Dimensional

You can declare one dimensional array in any of the following ways:

  • int myArray[]; 
  • int[] myArray;


You can declare multi-imensional array in any of the following ways:

  • String myArray[][];
  • String[][] myArray;

Construct Array

After you have declared array, you need to construct array,

int myArray[];  //declare

myArray[ ] = new int[5];  //construct array and assign it to myArray variable


The above code will put an array object capable of holding 5 elements on the heap. Each element in array will be of type int and their default value will be 0.


Short-cut: Declare and construct in one statement

int myArray[] = new int[5];

This basically combines the two statements that we saw above. Thus allows us to declare and construct array in one statement.


If you don’t provide size during array construction then your code will not compiler.

For example, int myArray[ ] = new int[ ]; //compiler error as size not declared

Initialize array

Initializing array simply means adding value to the constructed array. Your array can hold primitive values or objects.

Different ways of initializing values:


Or you can simply write the same in single line:

int myArray[] = {2,33,24,11};  //aray with size 4

In next chapter we will see few examples on array.



Please Share this page
Views : 285
Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!