Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconArray in Java: What You Need To Know?

Array in Java: What You Need To Know?

Last updated:
15th Jun, 2023
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
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!

Ads of upGrad blog

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

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.

Explore our Popular Software Engineering Courses

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.

Explore Our Software Development Free Courses

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.

In-Demand Software Development Skills

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

Read our Popular Articles related to Software Development

Initialising Arrays with Precise Values 

Syntax to initialize an array with unique values:

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};

Using loops to traverse and modify array elements:

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);

Sorting Arrays the Usage of Integrated Capabilities

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:

Ads of upGrad blog

Arrays.Type(numbers);

Searching for Specific Elements in an Array

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;

    }

}

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.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

1How 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.

2How 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.

3What 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).

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Full Stack Developer Salary in India in 2024 [For Freshers &#038; Experienced]
907173
Wondering what is the range of Full Stack Developer salary in India? Choosing a career in the tech sector can be tricky. You wouldn’t want to choose
Read More

by Rohan Vats

15 Jul 2024

SQL Developer Salary in India 2024 [For Freshers &#038; Experienced]
902296
They use high-traffic websites for banks and IRCTC without realizing that thousands of queries raised simultaneously from different locations are hand
Read More

by Rohan Vats

15 Jul 2024

Library Management System Project in Java [Comprehensive Guide]
46958
Library Management Systems are a great way to monitor books, add them, update information in it, search for the suitable one, issue it, and return it
Read More

by Rohan Vats

15 Jul 2024

Bitwise Operators in C [With Coding Examples]
51783
Introduction Operators are essential components of every programming language. They are the symbols that are used to achieve certain logical, mathema
Read More

by Rohan Vats

15 Jul 2024

ReactJS Developer Salary in India in 2024 [For Freshers &#038; Experienced]
902674
Hey! So you want to become a React.JS Developer?  The world has seen an enormous rise in the growth of frontend web technologies, which includes web a
Read More

by Rohan Vats

15 Jul 2024

Password Validation in JavaScript [Step by Step Setup Explained]
48976
Any website that supports authentication and authorization always asks for a username and password through login. If not so, the user needs to registe
Read More

by Rohan Vats

13 Jul 2024

Memory Allocation in Java: Everything You Need To Know in 2024-25
74112
Starting with Java development, it’s essential to understand memory allocation in Java for optimizing application performance and ensuring effic
Read More

by Rohan Vats

12 Jul 2024

Selenium Projects with Eclipse Samples in 2024
43493
Selenium is among the prominent technologies in the automation section of web testing. By using Selenium properly, you can make your testing process q
Read More

by Rohan Vats

10 Jul 2024

Top 10 Skills to Become a Full-Stack Developer in 2024
229999
In the modern world, if we talk about professional versatility, there’s no one better than a Full Stack Developer to represent the term “versatile.” W
Read More

by Rohan Vats

10 Jul 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon