In this post we’ll talk about one of the programming construct; Array in Java. Topics covered are how to declare an array, how to create and initialize an array, how to store elements in an array and how to access those elements using array indexes, types of arrays in Java.
Array in Java
Array in Java is a fundamental programming construct that holds a fixed number of values of a single type. For every type there is a corresponding array type so you can have array of any primitive data type like int, double, char etc. as well as an array of objects like String, BigInteger or any user defined object.
Array elements are stored in contiguous memory locations, in case of primitive types values are stored in those locations, for an array of objects array holds reference to those objects.
Each item in an array is called an element, and each element is accessed by its numerical index. Index numbering begins with 0. If there are n elements in an array, you can access them using indices from 0 to n-1.
Following image shows an array of length 10 and its type is int.
- Declaring an array in Java
- Creating and Initializing an array in Java
- Creating array using new operator
- Using array literal (combining creation and initialization)
- Java array creation examples
- ArrayIndexOutOfBoundsException- Run time array index checking
- Multidimensional arrays in Java
- Multidimensional array Java example
Declaring an array in Java
Syntax for Java array declaration is as follows-
type[] array-name; Or type array-name[];
Note that both ways of array declaration are valid but as per Java doc type array-name[] form is discouraged. That’s what Java doc says “However, convention discourages this form; the brackets identify the array type and should appear with the type designation”.
As per syntax an array declaration has two components: the array's type and the array's name. An array's type is written as type[], where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array. An array's name can be any variable name provided that it follows the rules and conventions for naming variables.
Some examples of declaring array in Java-
int[] anArrayOfIntegers; double[] tempArray; String[] arrayOfNames; Employee[] arrayOfEmployees // Where Employee is a custom class
Creating and Initializing an array in Java
Note that array declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.
For creating an array in Java you use one of the following ways-
- Create an array using new operator.
- Using array literal where creation and initialization is done in a single line.
Creating array using new operator
Syntax for creating array using new operator is-
array-name = new type[size];
here type is the data type of the array elements.
size is the number of elements that can be stored in the array. array-name – variable that holds reference to the created array.For example creating an array of length 10 that stores int values.
int[] intArray; // declaration intArray = new int[10]; // creation
You can also combine these both steps of declaration and creation into a single step.
int[] intArray = new int[10];Important point-
When an array is created using new operator its elements are automatically initialized to the default value which is as follows-
- 0 for numeric types.
- false for boolean.
- null for object references (array of objects).
Using array literal (combining creation and initialization)
You can also use the short cut syntax to create and initialize an array where curly braces {} are used to provide the values separated by commas.
For example-
int[] anArray = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
Here the length of the array is determined by the number of values provided between braces and separated by commas.
Java array creation examples
1- Following Java example creates an array of integers, initialize it and later access the array values using array indices in a for loop.
public class ArrayExample { public static void main(String[] args) { // creating array int[] num = new int[5]; // initializing array num[0] = 10; num[1] = 20; num[2] = 30; num[3] = 40; num[4] = 50; for(int i = 0; i < num.length; i++){ System.out.println("element at index " + i + " is " + num[i]); } } }Output
element at index 0 is 10 element at index 1 is 20 element at index 2 is 30 element at index 3 is 40 element at index 4 is 50
2- In this example we’ll see how to create an array of objects. In the code an array of type Employee is created where Employee is a user defined class. This array can store objects of type Employee.
class Employee{ private int empId; private String empName; Employee(int empId, String empName){ this.empId = empId; this.empName = empName; } public int getEmpId() { return empId; } public void setEmpId(int empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } } public class ArrayExample { public static void main(String[] args) { // creating array Employee[] empArray = new Employee[5]; // initializing array empArray[0] = new Employee(1, "Cary"); empArray[1] = new Employee(2, "Gregory"); empArray[2] = new Employee(3, "Clint"); empArray[3] = new Employee(4, "James"); empArray[4] = new Employee(5, "John"); for(Employee emp : empArray){ System.out.println("Id- " + emp.getEmpId() + " Name- " + emp.getEmpName()); } } }Output
Id- 1 Name- Cary Id- 2 Name- Gregory Id- 3 Name- Clint Id- 4 Name- James Id- 5 Name- John
ArrayIndexOutOfBoundsException- Run time array index checking
A Java array guarantees that it cannot be accessed outside of its range. Java has strict run-time check for any out of range index. Trying to access array index out of the range, either negative number or positive number, will result in ArrayIndexOutOfBoundsException which is a run-time exception.
public class ArrayExample { public static void main(String[] args) { // creating array int[] num = new int[5]; // initializing array num[0] = 10; num[1] = 20; num[2] = 30; num[3] = 40; num[4] = 50; // trying to access out of range index int i = num[5]; } }Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at com.knpcode.programs.ArrayExample.main(ArrayExample.java:34)
As you can see here array of length 5 (index 0 to 4) is created. Trying to access index 5 which is out of range results in ArrayIndexOutOfBoundsException.
Multidimensional arrays in Java
You can also declare multidimensional arrays in Java which are actually array of arrays. To declare a multidimensional array, specify each additional dimension using another set of square brackets.
For example creating a two dimensional array of integers-
int[][] matrix
Multidimensional array Java example
public class ArrayExample { public static void main(String[] args) { // 2-D array int[][] matrix = new int[3][3]; // initializing array for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ // assigning random numbers matrix[i][j] = (int)(Math.random() * 10); } } // Displaying array elements for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ System.out.print(matrix[i][j] + " "); } System.out.println(); } } }Output
9 1 2 4 2 0 0 7 8
Reference: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
That's all for the topic Array in Java. If something is missing or you have something to share about the topic please write a comment.
You may also like
No comments:
Post a Comment