Array Java - Comprehensive Guide on Arrays in Java

Arrays in Java is a basic data structure to keep a known number of same values. For example, you can have an array of 10 integers or an array of 20 objects of class Point and so on.

Arrays are one of the most heavily used data structure in java programming due to their simplicity, performance and usability in different scenarios.

Array Java - Basics

Array is a collection of objects of same type and one can store only fixed number of objects in an array. This fixed number is called the length or size of array.

Individual elements in array can be accessed through index access. For example, anArray[0] or anArray[5] and so on.

Java Array Declaration - How to Declare and Create

Syntax to declare an array

// array declaration for a type, e.g. int

int[] anArray;
// or
int anArray[];

How to create an array of fixed size

// create an array of integers with size 10
anArray = new int[10];

Array Java Initialization - Simple usage of Array

How to use an array and do assignment and access. Please note that array indexing starts from 0 and goes till length-1

int anArray[] = new int[4]; // array initialization by individual assignment a[0] = 10; a[1] = 20; a[3] = 30; a[4] = 40; // array access for 4th element will print 40 System.out.println(a[3]);

One can also initialize an array in a single line using:

int anArray[] = {10, 20, 30, 40};

Java Array Length

One can find java array length by simply calling .length over an array.

int size = anArray.length

Array Java - Looping over an array

Once can easily loop (iterate) over all elements in an array using simple for loop.

// how to loop or iterate over an array
for(int i = 0; i < anArray.length; i++) {

Array Java Performance & Weakness

From usability point of view, Java Arrays are very versatile and useful in variety of scenarios. All operations on Arrays are O(1) - means assignment as well access of an array element is as fast as possible.

Their only shortcoming is that their size is fixed and one can't grow their size at runtime. If one needs to have dynamic size array, you should use List in Java