How Arrays In Java Work

Introduction

This article explains how arrays in Java works. The Netbeans 7.3.1 IDE is used for sample programs.

Java Array

Normally, an array is a collection of similar type of elements having a contiguous memory location.

In terms of computer programming languages, an array is an object that contains elements of similar data types. It is a data structure where we can store similar types of elements. We can store only fixed elements in an array.

An Array is indexed based; the first element of the array is stored at index 0, the last at the last index.

fig-15.gif

Advantages

  • Code Optimization

          Beneficial for retrieving or sorting the data easily.

  • Random Access

          We can randomly get any data located at any index position.

Disadvantage

  • Size limit

          Arrays are limited in size (the size is declared only once and it doesn't grow its size during runtime). To solve this problem, collections are used in Java.

Types of arrays

  1. Single-dimensional
  2. Multi-dimensional

1. Single-dimensional

Syntax

data_type[] reference_variable; or
data_type []reference_variable; or
data_type reference_variable[];

Initialization

reference_variable=new data_type[size];

Example

Open the Netbeans IDE then click on "File" -> "New project" then choose "Java project" then provide a name (for example "JavaArray") then click on "Ok".

Then right-click on our project and choose "New" -> "Java class" and then give your class name (as ArrayEx1.java) and click "Ok" then provide the following code there.

Fig-2.jpg

Output

Run our file (ArrayEx1.java); we will see the following output:

fig-3.jpg

How to declare an array

We can declare an array using the following syntax:

int a[]={33,22,11,00};//declaration

Example

Create another file ArrayDecEx.java

Fig-4.jpg

Output

Fig-5.jpg

How to pass array in methods

We can pass the array in methods in the following ways.

Example

Create ArrayPassEx.java

Fig-6.jpg

Output

Fig-7.jpg

Multi-dimensional array

This is a 2-dimensional or multi-dimensional array; in this, data is stored using a row and column based index (also known as matrix form).

Syntax of 2-d array

int[][] array=new int[5][5]; // contains 5 rows and 5 columns

Example

Create MltiDimArrayEx.java

Fig-8.jpg

Output

Fig-9.jpg

How to copy an array

We can copy an array to another array using the arraycopy method of the System class.

Example

Create ArrayCopyEx.java

fig-10.jpg

Output

fig-12.jpg