Array in Java (part 1)

What is an array?

In Java, an array is a group of like-type variables which are sequent addresses on memory. The size of an array is absolute and cannot be changed during program execution.

The elements in an array are indexed by number and start with 0. The index of an element is like its address which helps us access the element’s value.

The following is an example of an array of the integers.

One dimension array
One dimension array

In Java, an array may be 1 dimension , 2 dimensions or n-dimensions. in 2 dimensions array, the element is indexed by 2 values which are row and column. For example:

Two dimensions array
Two dimensions array

Declaring an array in Java

Declaring an array in java with empty value:

//1 dimension
< data type >[] name-of-variable = new < data type >[leng-of-array];
//2 dimensions
< data type >[][] name-of-variable = new < data type >[num-of-rows][num-of-columns];
//1 dimension array
int[] arr = new int[10];

//2 dimensions array
int[][] arrb = new int[5][6]

Declaring an array with existed values:

int[] a = {1,2,3,4};
String[][] str = {{"this", "is", "the", "first", "row"},
                  {"this", "is", "the", "second", "row"}};

Assigning and accessing the values

Assigning the values into an empty array, with a short array, we can adding the values by selecting the index.

int[] arr1 = new int[3];
arr1[0] = 2;
arr[1] = 3;
arr[2] = 4;

However, in the case of longer array, we have to use another way to adding the values. Using for loop is an example.

int[] arr = new int[30];
int values = 1;
for(int i = 0; i < arr.length; i++){
    arr[i]= values;
// the array will be [1,3,5,7 ....];

Similar with assigning value, we can access the value by using the index of value. For example:

String[] arr = {"this","is","a","string"};

The out put will be


Or in the case we want to print all of the elements, we can use the For each loop

String[] arr = {"this","is","a","string"};
for(String str : arr){

the output will be


For printing the whole array

import java.util.*;	
public class arraysTest{
	public static void main(String[] args){
		String[] arr = {"this","is","a","string"};

The output will be

[this, is , a, string]


We have gone through some basic things about array in Java. In part 2, I will write about some useful methods of Array class in java. Thanks for your reading.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a website or blog at

Up ↑

%d bloggers like this: