Array in Java: What You Need To Know?
By Rohan Vats
Updated on Jun 16, 2023 | 8 min read | 5.8k views
Share:
For working professionals
For fresh graduates
More
By Rohan Vats
Updated on Jun 16, 2023 | 8 min read | 5.8k views
Share:
Table of Contents
After going through the primitive data types of java, many of us will have a question can we store more than one entry sequentially in the disk?. Arrays in java would be the answer to our query.
An array is a data structure that stores the entries of the same data type sequentially. An array reduces the duplication of code and makes it simple. When we want to store a considerably big number of values, say 50 values then assigning each value to a variable contradicts the simplicity of a code.
An array overcomes this issue we can assign all these values to a single array but remember that an array can store only values of the same data type.
Let’s get started!
To use an array we need to declare it and we must specify the data type of the variables we want to store in the array. Similar to all the programming languages java also has a syntax to be followed for declaration.
int[] array; //type1
int array[]; //type2
And the syntax of creating an array goes as follows “data_type[] array = new array[array_length]”. We need to assign the length of the array at the time of creating it and the size cannot be increased after creating. After creating an array by specifying the length, it just assigns an empty array to that variable and we can push the values into it later. Let’s walk through the code for that.
And the syntax of creating an array goes as follows “data_type[] array = new array[array_length]”. We need to assign the length of the array at the time of creating it and the size cannot be increased after creating. After creating an array by specifying the length, it just assigns an empty array to that variable and we can push the values into it later. Let’s walk through the code for that.
int[] array = new int[10]; //declaration and
//creating a new array
//assigning values
array[0]=1;
array[1]=5;
array[8]=9;
//method 2
int[] array = {1, 2, 3, 4, 5};
System.out.print(int[0]);
Initially, all the positions are filled with zeroes in an integer array and we can override those values with our values by mentioning the index in the square brackets. In the above snippet, “method 2” is another way of creating an array.
We can use a for loop or a while loop for looping over an array, where we increment the index for each iteration. Remember that accessing an element with an index greater than the length of the array will throw an exception.
int[] array={1,2,3,4,5};
for(int i=0;i<5;i++){
System.out.print(array[i]+" ");
}
The above code snippet prints “1 2 3 4 5 ” as the output.
There’s also another interesting loop called “for-each loop” for iterating over the loop.
float[] array={1.2f,2.3f,3.4f,4.5f,5.6f};
for(float f:array){
System.out.print(f+" ");
}
The above code snippet shows the implementation of the for-each loop, where the variable float changes the value to the next entry in the array at each iteration. This implementation doesn’t need any index variable.
Checkout: A Complete ArrayList in Java: What You Need to Know
The Arrays class in java comes with many predefined methods that are generalized to all primitive data types. For example, if I want to sort an array with all integers and an array with all floats then I can use the same method for both cases.
Let’s walk through a few of the predefined array methods.
This method sorts the given array in the ascending order and updates the sorted array, as already discussed this method is overloaded for all primitive data types in java. This public method doesn’t return anything since it’s of the void return type.
Arrays.sort(array_name) is the syntax to be followed.
float[] array={2.2f,1.3f,5.4f,3.5f,7.6f};
Arrays.sort(array);
for(float f:array){
System.out.print(f+" ");
}
The above snippet will print “1.3 2.2 3.5 5.4 7.6 “ as expected.
This method fills the array with the variable we passed in the function call. This method replaces a naive implementation of looping over the array and assigning a value to that position.
Arrays.fill(array_name, value) is the syntax to be followed.
float[] array={2.2f,1.3f,5.4f,3.5f,7.6f};
Arrays.fill(array,9.8f);
for(float f:array){
System.out.print(f+" ");
}
The above snippet will replace all the entries in the array with 9.8.
This method expects two arrays as the parameter and returns true if all the elements in array 1 are equal to all the elements of array 2. Remember that this method returns false if both the arrays have different lengths, or if the order of elements is different.
Arrays.equals(array_1, array_2) is the syntax to be followed.
float[] array1={2.2f,1.3f,5.4f,3.5f,7.6f};
float[] array2={2.2f,1.3f,5.4f,3.5f,7.6f};
float[] array3={2.2f,1.3f,3.5f,5.4f,7.6f};
System.out.println(Arrays.equals(array1,array2)); //line1
System.out.println(Arrays.equals(array1,array3)); //line2
The above snippet will print True for line1 and False for line2 For a further read on various array methods in java, have a look at their documentation.
Arrays would be of no use if we can’t use them in functions. But Java never lets you down, we can pass an array, return an array, and use an array in java function.
Let’s walk through them.
We need to specify the data type of the array in function declaration when we want to pass an array to the Java function. This is almost similar to passing a primitive data type to function. Similarly, when we return an array, we need to declare the array with the array as the return type.
public static float[] sorted(float[] array){
Arrays.sort(array);
return array;
}
public static void main(String args[]){
float[] array1={2.2f,1.3f,5.4f,3.5f,7.6f};
float[] array2=sorted(array1);
for(float f:array2)
System.out.print(f+" ");
}
The above snippet prints “1.3 2.2 3.5 5.4 7.6” as expected.
Datatype[] arrayname = {value1, value2, value3, …};
For example, we will create an array of integers with the following values:
int[] numbers = {1, 2, 3, 4, 5};
We can use loops to traverse and modify array elements. The ‘for’ loop is quite common for traversing arrays. For instance, we can use a ‘for’ loop to print all values in an array of numbers:
for(int i = 0; i < numbers.length; i++){
System.out.println(numbers[i]);
}
We can create arrays using the System.Arraycopy() technique. This technique copies the source array, the beginning index of the source array, the destination array, the beginning index of the vacation spot array, and the variety of elements to be copied. For example, we can copy the variety array to some other array referred to as numbersCopy:
int[] numbersCopy = new int[numbers.length];
System.arraycopy(numbers, 0, numbersCopy, 0, numbers.length);
Java gives integrated capabilities for the array’s sorting program in Java. We can use the Arrays.Type() approach to sort arrays in ascending order. For example, we can set up the numbers in ascending order:
Arrays.Type(numbers);
To search for a specific detail in an array, we can use a loop to iterate through the array and evaluate every detail to the detail we are searching for. For instance, we can search for the range 3 within the numbers array:
int searchValue = 3;
for(int i = 0; i < numbers.length; i++){
if(numbers[i] == searchValue){
System.out.println("Found at index " + i);
break;
}
}
Now that you are aware of arrays in java. Understood about Initialization and declaration of the array. Explored various ways of iterating over the array. Walked through a few of the predefined array methods and accessing arrays in methods. You are power-packed with a useful data structure in java, start using it now!
If you’re interested to learn more about Java, OOPs & full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.
408 articles published
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
India’s #1 Tech University
Executive PG Certification in AI-Powered Full Stack Development
77%
seats filled
Top Resources