Arrays in Java

Java Arrays

Java Arrays are data structures which store a fixed number of values of same data type. An array is used to store data of same data type in a sequence and is easy to access and modify.

Instead of defining every variable individually of the same type we create an array and simply add all values in it. Array saves values in different indexes and they can access using these indexes for later use.

Initializing or declaration of array in Java:

Syntax: data_type [ ] variable_name;

Example: int [ ] a;

In java there are so many ways of creating arrays and assign values to it some are following.

int [ ] arr;

int arr[ ];

int arr[ ] = new int[ array_length ];

int [ ] array = {value1, value2 … };

Java Arrays
Arrays in Java


Looping Array:

As we see in above example to print every value of array we have to write separate condition for every index of an array so to reduce this problem loops are used like for loop, while loop and do while also.

Example using for loop:

Example using while loop:

foreach loop in Java:

In java for access array all values in one go a special loop is used that’s called foreach loop.


for( data_type_same_to_array_data_type variable_name : array_name){



Array as Parameters/argument in functions:

We can send array as a parameter in any function and this function also receive it as an argument and function in java also return an array.

Array as Parameter:

Array as return type of function:

To return an array the function must be having a return data type of array. It mean if a function return integer array the function data type must be int[ ] a();

2D array in Java:


Two Dimensional Arrays in Java
2D arrays in java

In the next tutorial, you will learn to create and use ArrayList in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *