If you are interested to learn about the Java break and Continue
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value To declare an array, define the variable type with square brackets:
String[] cars;

We have now declared a variable that holds an array of strings. To insert values to it, you can place the values in a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};
Advantages
- Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
- Random access: We can get any data located at an index position.
Disadvantages
- Size Limit: We can store only the fixed size of elements in the array. It doesn’t grow its size at runtime. To solve this problem, collection framework is used in Java which grows automatically.
Access the Elements of an Array
You can access an array element by referring to the index number. This statement accesses the value of the first element in cars:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars[0]); // Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Change an Array Element
To change the value of a specific element, refer to the index number:
Example
cars[0] = "Opel";
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; cars[0] = "Opel"; System.out.println(cars[0]); // Now outputs Opel instead of Volvo
Array Length
To find out how many elements an array has, use the length
property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; System.out.println(cars.length); // Outputs 4
Java Arrays Loop
You can loop through the array elements with the for
loop, and use the length
property to specify how many times the loop should run. The following example outputs all elements in the cars array:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (int i = 0; i < cars.length; i++) { System.out.println(cars[i]); }
Loop Through an Array with For-Each
There is also a “for-each” loop, which is used exclusively to loop through elements in arrays:
Syntax
for (type variable : arrayname) { ... }
The following example outputs all elements in the cars array, using a “for-each” loop:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"}; for (String i : cars) { System.out.println(i); }
The example above can be read like this: for each String
element (called i – as in index) in cars, print out the value of i. If you compare the for
loop and for-each loop, you will see that the for-each method is easier to write, it does not require a counter (using the length property), and it is more readable.
Java Multi-Dimensional Arrays
A multidimensional array is an array of arrays. To create a two-dimensional array, add each array within its own set of curly braces:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
myNumbers is now an array with two arrays as its elements. To access the elements of the myNumbers array, specify two indexes: one for the array, and one for the element inside that array. This example accesses the third element (2) in the second array (1) of myNumbers:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} }; int x = myNumbers[1][2]; System.out.println(x); // Outputs 7
We can also use a for loop
inside another for loop
to get the elements of a two-dimensional array (we still have to point to the two indexes):
Example
public class Main { public static void main(String[] args) { int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} }; for (int i = 0; i < myNumbers.length; ++i) { for(int j = 0; j < myNumbers[i].length; ++j) { System.out.println(myNumbers[i][j]); } } } }
Declaration, Instantiation and Initialization of Java Array
We can declare, instantiate and initialize the java array together by:
int a[]={33,3,4,5};//declaration, instantiation and initialization
Let’s see the simple example to print this array.
//Java Program to illustrate the use of declaration, instantiation //and initialization of Java array in a single line class Testarray1{ public static void main(String args[]){ int a[]={33,3,4,5};//declaration, instantiation and initialization //printing array for(int i=0;i<a.length;i++)//length is the property of array System.out.println(a[i]); }}
Output:
33
3
4
5
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop.
The syntax of the for-each loop is given below:
for(data_type variable:array){ //body of the loop }
Let us see the example of print the elements of Java array using the for-each loop.
//Java Program to print the array elements using for-each loop class Testarray1{ public static void main(String args[]){ int arr[]={33,3,4,5}; //printing array using for-each loop for(int i:arr) System.out.println(i); }}
Output:
33
3
4
5
Passing Array to a Method in Java
We can pass the java array to method so that we can reuse the same logic on any array .Let’s see the simple example to get the minimum number of an array using a method.
//Java Program to demonstrate the way of passing an array //to method. class Testarray2{ //creating a method which receives an array as a parameter static void min(int arr[]){ int min=arr[0]; for(int i=1;i<arr.length;i++) if(min>arr[i]) min=arr[i]; System.out.println(min); } public static void main(String args[]){ int a[]={33,3,4,5};//declaring and initializing an array min(a);//passing array to method }}
Output:
3
Anonymous Array in Java
Java supports the feature of an anonymous array, so you don’t need to declare the array while passing an array to the method.
//Java Program to demonstrate the way of passing an anonymous array //to method. public class TestAnonymousArray{ //creating a method which receives an array as a parameter static void printArray(int arr[]){ for(int i=0;i<arr.length;i++) System.out.println(arr[i]); } public static void main(String args[]){ printArray(new int[]{10,22,44,66});//passing anonymous array to method }}
Output:
10
22
44
66
Returning Array from the Method
We can also return an array from the method in Java.
//Java Program to return an array from the method class TestReturnArray{ //creating method which returns an array static int[] get(){ return new int[]{10,30,50,90,60}; } public static void main(String args[]){ //calling method which returns an array int arr[]=get(); //printing the values of an array for(int i=0;i<arr.length;i++) System.out.println(arr[i]); }}
Output:
10
30
50
90
60
Array Index Out Of Bounds Exception
The Java Virtual Machine (JVM) throws an ArrayIndex Out Of Bounds Exception if length of the array in negative, equal to the array size or greater than the array size while traversing the array.
//Java Program to demonstrate the case of //ArrayIndexOutOfBoundsException in a Java Array. public class TestArrayException{ public static void main(String args[]){ int arr[]={50,60,70,80}; for(int i=0;i<=arr.length;i++){ System.out.println(arr[i]); } }}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80