Programs

Array in Java: What You Need To Know?

Introduction

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!

Declaration and Initialization

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

We can declare an array in both ways as shown in the above code snippet. “Type2” is a traditional way of declaring an array that is borrowed from c/c++. Once we are done with declaring an array we need to create a new array and this can be accomplished by using the new keyword.

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.

Looping Over The 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

Predefined Methods

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.

 

  • sort()

 

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.

  • fill()

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.

  • equals()

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.

Accessing Arrays in Methods

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. 

Read: MATLAB Data Types: Everything You Need to Know

Conclusion

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.

How is an array different from a linked list?

In an array, data elements are stored in contiguous allocation in the memory, whereas in a linked list, the data elements are stored in a non-contiguous manner. Arrays require compile-time allocation of data, whereas linked lists require dynamic data allocation, i.e., run-time allocation. Linked lists require more memory than arrays as we also need to add a reference to the next node with every element. Linked lists are helpful when we do not know how much space we require for the program, whereas in arrays, you have to declare the size of the list upfront. Arrays can be directly accessed through the index value in the list, whereas a linked list cannot be accessed directly; it requires traversing.

How is an array different from an Array list?

Arrays can be single-dimensional or multi-dimensional, but array lists can only be single-dimensional. For traversing elements in an array, for() loop is used, whereas an iterator is used for traversing elements in an array list. The ‘length’ keyword is used to get the size of an array, whereas size() is used to get the size of an array list. An array has a fixed size, whereas an array list has a dynamic size that can be increased and decreased based on the requirements. Arrays are relatively faster than array lists because of their fixed size. Autoboxing is required to store primitive data types in an array list.

What is Quicksort, and how does the worst-case time complexity occur

Quicksort is an in-place algorithm that follows the divide and conquers approach for sorting the elements in a list. In this, we need to select a pivot element, and we shift all elements smaller than it to the left side of the pivot and all elements larger than the pivot to the right side of the pivot. After each iteration, the pivot element gets placed at its correct position in the array. The worst-case time complexity is achieved by giving a sorted list as the input. By this, the time complexity gets increased from O(N logN) to O(N^2).

Want to share this article?

Prepare for a Career of the Future

INDUSTRY TRUSTED LEARNING - INDUSTRY-RECOGNIZED CERTIFICATION.
Learn More

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Let’s do it!
No, thanks.