Arrays in Java

Array is a collection of homogeneous type of data. That means, an array can contain similar type of data only.

Lets say we want to store ages of 5 students in a class. So what we can do is we declare 5 different variables to store ages. For example: age1, age2, age3, age4 and age5.

This is when array comes in use. Instead of declaring individual variables, we can declare only one variable and store all data accessible by its index number.

What is index number?
Each slot/data in the array can be referenced with a number and the reference number is index.


Declaring Array

Declaring Array is as simple as declaring variable. But we must add square brackets( [ ] ) after the data type. Syntax:

DataType[] variable;


Creating Array

After declaring Array it only says which data type will be stored in variable as array. To create actual array, we can insert data in it or give the size of array to insert data later.

To insert values, we can place the values in a comma separated list inside curly braces. Syntax:

variable = {value1, value2, ... , valuen};

To create an array when data values are currently unknown, we can allocate one using new keyword and size. Syntax:

variable = new DataType[size];


Wrapping Up

We can combine all steps above in one statement instead of writing in multiple lines. Here is how to do it:

DataType[] variable = {value1, value2, ... , valuen};
(OR)
DataType[] variable = new DataType[size];


Examples:

int[] age = {23, 45, 34, 28, 40}; String[] name = {"John", "Harry", "Javier"}; char[] grade = new char[5]; int[] mark = new int[5]; boolean[] gender = new boolean[5];


Break and Continue in Java Previous Next Arrays in Java | Part 2