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.
Advantages
Beneficial for retrieving or sorting the data easily.
We can randomly get any data located at any index position.
Disadvantage
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
- Single-dimensional
- 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.
Output
Run our file (ArrayEx1.java); we will see the following output:
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
Output
How to pass array in methods
We can pass the array in methods in the following ways.
Example
Create ArrayPassEx.java
Output
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
Output
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
Output