Arrays in java are the most widely used data structure that stores multiple values of the same data type in sequential order. The array has a fixed length and the index starts from 0 to n-1 where n is the length of an array. We can use arrays class in Java to store any type of value like String, integer, character, byte, and even user-defined objects. We will learn how to initialize array in Java?
Below is the diagrammatic representation of a single-dimensional array of integers having 11 elements.
Table of Contents
Java Arrays Features
- The array has a fixed size and cannot be changed
- Since the array is index-based, it is easy to access random elements
- Allocates continuous memory for array elements.
- Can store both primitive and non-primitive data values
How to declare an Array in Java?
Java Arrays declaration
An array can be declared in the below ways. Array declaration contains 2 parts, first is the datatype of the elements which we need to store in an array(like int, String, etc) and followed by the array name. [] brackets denote that it is an array. When we declare an array, it just tells the compiler that the variable is an array and does not actually create an array.
datatype[] arrayName; (or)
datatype []arrayName; (or)
datatype arrayName[]; –> Normally we do not prefer to use this method though it is valid.
Example of array declaration
int[] arrNumbers; String[] arrNames; float[] arrValues; boolean[] arrBoolean; char[] arrLetters; byte[] arrBytes; double[] arrWeight;
How to create an Array in Java?
String Array in Java
We create an array using the new operator. In this, we specify the size of an array in [] which denotes the amount of memory required to store the array variable.
arrname = new datatype[size];
We can also declare and create an array in a single statement as below. The first statement creates an integer array named numbers of size 5. The second creates a String array named names of size 2
int[] arrNumbers = new int[5]; String[] arrNames = new String[2];
How to initialize array in Java?
How to instantiate an array?
Array initialization or instantiation means assigning values to an array based on array size. We can also create and initialize (instantiate) an array together (Refer to Method 1 below). In this case, the number of elements denotes the length or size of an array. In Method 2, we are assigning values separately t0 each element. Since the array index starts with 0 and array size here is 3, the 3rd element occupies 2nd position which is n-1 where n is the size of the array.
//Method 1 int[] arrNumbers = {1,2,3}; //Method 2 int[] arrNumbers = new int[3]; arrNumbers[0] = 1; arrNumbers[1] = 2; arrNumbers[2] = 3;
Accessing Array elements In Java
We access array elements by using its index value. Generally, we use For loop or For each loop to access the array elements since all the elements are of the same type and have a fixed size.
Example: Create, Initialize and Access Array elements
Here, we are creating and initializing an array of strings in a single statement and accessing each element using for loop
public class ArrayDemo1 { public static void main(String[] args) { String[] arrMonths = {"May","June","July"}; System.out.println("Length of array is: " + arrMonths.length); for(int i=0;i<arrMonths.length;i++) { System.out.println(arrMonths[i]); } } }
Output: Length of array is: 3 May June July
Example: Another method of initializing array and accessing array elements
In the below example, we first declare and create an array of integers and then assign values to individual array elements. Here, we are using for each loop to access the array elements.
public class ArrayDemo2 { public static void main(String[] args) { int[] numbers = new int[5]; numbers[0] = 100; numbers[1] = 101; numbers[2] = 103; numbers[3] = 104; numbers[4] = 105; for(int i: numbers) { System.out.println(i); } } }
Output: 100 101 103 104 105
types of arrays in Java
There are 2 types of arrays in Java:
- Single dimensional array – This contains only 1 row and 1 column. All the above examples belong to a single dimensional array
- Multidimensional array – This contains multiple rows and multiple columns. In other words, it is an array of arrays where all rows have same number of columns. Eg: 2*2 matrix
- Jagged array – Each row contains a different number of columns
Multidimensional Arrays In java
Multidimensional arrays can have multiple rows and columns. The index in the first [] represents rows and the second [] represents columns.
Eg: int[][] a = new int[2][3]
This means the array contains 2 rows and 3 columns. Below is the diagrammatic representation of a multidimensional array
Example of creating multidimensional arrays of Strings
The below example shows how to create, declare, and access multidimensional array elements. Here, we directly access array elements using the row and column index.
public class ArrayMulti { public static void main(String[] args) { String[][] arrNames = {{"John","Jacob"},{"Thomas","Martin"}}; System.out.println(arrNames[0][0] + " " + arrNames[0][1]); System.out.println(arrNames[1][0] + " " + arrNames[1][1]); } }
Output: John Jacob Thomas Martin
Example of a 2D array of integers
Here, we are creating a 2-dimensional array of integers having 2 rows and 3 columns. We assign the values to these array elements inside for loop. The 1st for loop denotes rows and 2nd for loop denotes columns.
public class ArrayMulti { public static void main(String[] args) { //Declare and create multidimensional array int[][] arrnum = new int[2][3]; for(int i=0;i<2;i++) { for(int j=0;j<3;j++) { //Assign values to array elements arrnum[i][j] = i+1; System.out.print(arrnum[i][j] + " "); } System.out.println(); } } }
Output: 1 1 1 2 2 2
Jagged Arrays in Java
A jagged array is also a 2-dimensional array having a different number of columns. In other words, each row has a different number of columns. Initializing a jagged array is different from that of a normal 2D array.
Initialization of Jagged Array
During array creation, we specify the number of rows. In this example, it is 2. In the next 2 statements, for each row array, we specify the number of columns. Here, 1st row has 3 columns and 2nd row has 4 columns.
int[][] arrnum = new int[2][]; arrnum[0] = new int[3]; arrnum[1] = new int[4];
Example of a jagged array by assigning values in for loop
public class JaggedArray { public static void main(String[] args) { int[][] arrnum = new int[2][]; arrnum[0] = new int[3]; arrnum[1] = new int[4]; int val=1; //Assign values for(int i=0;i<arrnum.length;i++) { for(int j=0;j<arrnum[i].length;j++) { arrnum[i][j] = val; } } //Print the values for(int i=0;i<arrnum.length;i++) { for(int j=0;j<arrnum[i].length;j++) { System.out.print(arrnum[i][j] + " "); } System.out.println(); } } }
Output: 1 1 1 1 1 1 1
Jagged array example by initializing the values during array creation
public class JaggedArray { public static void main(String[] args) { int[][] arr = {{4,5,6},{1,2},{7,9,8}}; for(int i=0;i<3;i++) { for(int j=0;j<arr[i].length;j++) { System.out.print(arr[i][j] + " "); } System.out.println(); } } }
Output: 4 5 6 1 2 7 9 8
Java Array Methods
Below are the direct methods supported by Arrays in Java
Method | Description |
---|---|
void clone() | Clones the existing array values where references are not copied |
Boolean equals(Object 0) | Checks whether some other object is equal to the current object |
Class getClass() | Returns the classname |
String toString() | Returns a string representation of the object |
int length() | Returns length of the array |
Java Array Exceptions
Arrays in Java throws the below exception:
- ArrayIndexOutOfBoundsException: This occurs when the index value we specify is greater than the length of an array or when it is negative. This occurs mainly while assigning value or accessing array elements.
Copy an array
We can copy elements from one array to another using the method arraycopy of the class System.
Copy array syntax
public void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
src-source array object to copy from
srcPos – starting position in the source array
dest – destination array object to copy to
destPos – starting position in the destination array
length – number of array elements to copy
Example of copying an array
In the below example, we are copying 4 elements from the source array to destination array. Hence the output prints “java””
public class ArrayCopy { public static void main(String[] args) { char[] a = {'d','l','h','y','j','a','v','a','g','r','t'}; char[] b = new char[4]; System.arraycopy(a, 4, b, 0, 4); System.out.println(String.valueOf(b)); } }
Output: java
Pass array to a method
In Java, we can pass an array object to a method for further manipulation or other operations. The below example shows how we can pass an array object of integers to a method and perform the addition of all array elements.
public class ArrayDemo3 { public static void main(String[] args) { int[] num = {5,7,3,2,8}; add(num); } public static void add(int[] num) { int sum = 0; for(int i=0;i<num.length;i++) { sum = sum + num[i]; } System.out.println("Sum of array elements is : " + sum); } }
Output:
is : 25
Return array from a method
We can also return an array object from method to the main method after performing the required operation.
public class ArrayDemo4 { public static void main(String[] args) { String[] arr = getArrayValues(); for(String cities:arr) { System.out.println(cities); } } public static String[] getArrayValues() { String[] arrCities = {"Chennai","Bangalore","Delhi"}; return arrCities; } }
Output: Chennai Bangalore Delhi
Array manipulations
Arrays in Java belong to java.util package. There are several operations supported by java.util.Array class as mentioned below:
- We can use copyOfRange method of Array class to copy a range of elements from one array to another
- Search an array for specific value based on an index (Binary search)
- Compare to arrays to check equality using the equals method
- Use the fill method to fill an array to place a specific value at an index
- Sorting an array using the sort method
Creating an array using a user-defined object
In java, we can also create a user-defined object just like how we create an array of strings, integer, etc. This is an example of how we can create a Student array object and initialize the array object.
public class ArrayDemo5 { public static void main(String[] args) { Student[] s = new Student[2]; s[0] = new Student(111,"Ajit"); s[1] = new Student(112,"Biju"); } } class Student{ public int rollno; public String name; public Student(int rno,String n) { rollno = rno; name = n; } }
Conclusion
This tutorial provides a detailed description of Arrays Class in Java, types of arrays in Java, declare, create and initialize arrays with various illustrations.