Friday , March 22 2019
Home / Java / Arrays in java

Arrays in java

The array is a data structure which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java Array

Code Optimization: It makes the code optimized, we can retrieve or sort the data easily.
Random access: We can get any data located at any index position.

Disadvantage of Java Array

Size Limit: We can store only fixed size of elements in the array. It doesn’t grow its size at runtime. To solve this problem, collection framework is used in java.

Types of Array in java

There are two types of array.

  1. Single Dimensional Array
  2. Multidimensional Array

Single Dimensional Array in java

Syntax to Declare an Array in java

dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Instantiation of an Array in java

arrayRefVar=new datatype[size];

Example of single dimensional java array

Let’s see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.


Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};  //declaration, instantiation and initialization
Let’s see the simple example to print this array.


Passing Array to method in java

We can pass the java array to method so that we can reuse the same logic on any array.

Let’s see the simple example to get minimum number of an array using method.

Multidimensional array in java

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in java

dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];
Example to instantiate Multidimensional Array in java

int[][] arr=new int[3][3];//3 row and 3 column
Example to initialize Multidimensional Array in java


Example of Multidimensional java array

Let’s see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

What is the class name of java array?

In java, array is an object. For array object, an proxy class is created whose name can be obtained by getClass().getName() method on the object.



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

Syntax of arraycopy method

public static void arraycopy(
Object src, int srcPos,Object dest, int destPos, int length

Example of arraycopy method



About admin

Check Also

Internal Working of HashMap in Java

In this article, we will see how hashmap’s get and put method works internally. What ...

Leave a Reply