Java Array Tutorial

Array Tutorial : How to define and instantiate an array in java

This page is dedicated for array tutorial in java. An array stores a list of data or objects of the same type. It is a general rule that it should be of the same type since when we instantiate it, we are  already specifying the type of data the array is holding.

Moreover when you instantiate the array, we are already specifying the length or size of it, and we should always remember that the length or size of an array can never be changed. In short the array’s length is fixed.

Those objects in an array is called an element. And each element can be called through array index.

Index of an array starts at 0 thus the first element of an array is located at index 0. Moreover the last element is in size of an array – 1

Examples:

// array of primitive data type int of size 5, by default values are null

// array of Strings of size 2 since values were already declared during initialization

// multi dimensional array of strings. In short we have an 5 array of array strings with dimension of 2

// example code in instantiating an array of objects

How to set the elements of an array

// example source code to put the elements on an array

How to access the elements inside an array

// access the elements inside the array

// access all the elements inside the array using for loop

// print all contents of a java array using advance for loop (for-each)

How to copy elements of an array to another array

Using the arraycopy() method of System class, we would be able to copy all elements of an array or only specific elements of an array efficiently.

Syntax:

Example:

How to replace a specific element of an array

This is very simple scenario we just have to assign a value to the target index

Example:

I have also written a compilation of java tutorials on java array examples. This compilation contains source codes for specific scenarios which you can readily modify to suit your needs.