top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Array Length in Java

Introduction

Arrays are a fundamental concept in programming, serving as the primary data structure in many programming languages. Java provides significant array support, allowing developers to easily store and manage a bundle of things. Knowing the length of an array is a vital aspect of working with Java.

This tutorial will teach several ways to estimate array length in Java, along with thorough examples. 

Overview

In Java, an array is a collection of elements that can carry multiple values depending on the object's formation. It is vital to know the length of an array to execute separate operations, such as iterating through each member in the array, finding the sum of all elements, counting even/odd items, and so on. The length attribute determines the length of an array in Java, which is a property, not a function. The value of this attribute contains the total number of items in the array.

How To Initialize an Array in Java

Multiple methods exist to start an array in Java, depending on whether one wants to set default or particular values to the array entries. Here are various approaches to initialize an array in Java:

  • Setting up an array without values: An array can be set up to a specific size, and each element's default value is 0.

  • Array initialization after declaration: An array can also be created after declaration.

  • Giving values to an array's initial state: An array can also be begun while being created.

  • Putting default values in an array's initialization: Java allows starting an array with default values by using the new keyword with the array's data type and size enclosed in square brackets.

  • Initializing an array using a loop: Java also allows using a loop to create an array.

Here is an example to initialize an array:

int[] numbers = {1, 2, 3, 4, 5};
You can also initialize an array using For loop:
int size = 5;
int[] numbers = new int[size];
for (int i = 0; i < size; i++) {
    numbers[i] = i + 1;
}

Here is how we can initialize an array with a specific value using Arrays.fill():

import java.util.Arrays;
int size = 5;
int[] numbers = new int[size];
Arrays.fill(numbers, 0);

Finally, here is how we can initialize a two-dimensional array:

int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

Java array methods include an array.length that indicates the many items in the array. In contrast, the ArrayList class has a method called array.size() that indicates how many objects are in the collection. 

Java array length vs. size

The following table summarizes the difference between Java array length and size:

array.length

array.size()

Provides the length or capacity of the array

Provides the number of objects available in the ArrayList

Array length is set permanently when the array is initialized

ArrayList size can be changed dynamically

Array length is accessed using the dot operator followed by the keyword length

ArrayList size is accessed using the size() method

Array is static, so when one creates an array of size n, then n blocks (with default values) are created of array type

ArrayList is dynamic, so it can grow or shrink as needed

How To Determine the Length or Size of an Array in Java?

You can use various approaches to compute an array's length or size in Java.

  • One method for determining the size of an array is to use the array's length attribute. The length property returns the array's whole potential size, not just the number of elements used.

Example:

public class main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int size = numbers.length;
        System.out.println("Size of the array: " + size); // Output: 5
    }
}

In this example, we have an array numbers with values {1, 2, 3, 4, 5}. To determine the size of the array, we use the length attribute, which returns the number of elements in the array. We assign the value of numbers.length to the variable size and then print it. In this case, the output will be 5, indicating that the array has five elements.

By accessing the length attribute of an array, you can easily determine its size and use it for various purposes, such as iterating over the elements or performing operations based on the array's length.

  • The size() function of the java.util.ArrayList class is another method for determining the size of an array in Java. The length of an ArrayList in Java can be determined using the size() function, which returns the number of items presently contained in the ArrayList. Unlike the length property of an array, the size() method returns the number of elements in the collection that are accessible.

Example:

import java.util.ArrayList;
public class main {
    public static void main(String[] args) {
        ArrayList<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        int size = numbers.size();
        System.out.println("Size of the ArrayList: " + size); // Output: 3
    }
}

In this example, we create an ArrayList called numbers and add three integers to it using the add() method. To determine the size of the ArrayList, we use the size() method, which returns the number of elements present in the ArrayList. We assign the value of numbers.size() to the variable size and then print it. In this case, the output will be 3, indicating that the ArrayList contains three elements.

It's important to note that the size() method is specific to the ArrayList class and not applicable to regular arrays. If you are working with regular arrays, you should use the length attribute to determine the size of the array, as shown in the previous example.

Using Array Length In Java To Search A Value

To search for a value in an array using the length attribute in Java, you can iterate over the array elements and compare each element with the target value. Here's an example:

public class main {
    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5};
        int target = 3;
        boolean found = false;
        for (int i = 0; i < numbers.length; i++) {
            if (numbers[i] == target) {
                found = true;
                break;
            }
        }
        if (found) {
            System.out.println("The value " + target + " is found in the array.");
        } else {
            System.out.println("The value " + target + " is not found in the array.");
        }
    }
}

In this example, we have an array numbers with values {1, 2, 3, 4, 5} and a target value of 3. We initialize a boolean variable found as false. Then, we iterate over the array elements using a for loop and compare each element with the target value using the == operator.

If a match is found, we set found to true and break out of the loop. Otherwise, the loop continues until all elements have been checked. After the loop, we check the value of found and print an appropriate message indicating whether the target value was found in the array.

Finding the Minimum and Maximum Values in the Array

There are several ways to find the minimum and maximum values in an array in Java. To find the minimum and maximum values in an array in Java, you can use the Arrays.sort() method to sort the array in ascending order. After sorting, the minimum value will be the first element of the sorted array, and the maximum value will be the last element.

Example:

import java.util.Arrays;
public class main {
    public static void main(String[] args) {
        int[] numbers = {5, 2, 8, 1, 9, 4};
        Arrays.sort(numbers); // Sort the array in ascending order
        int min = numbers[0]; // Minimum value is the first element
        int max = numbers[numbers.length - 1]; // Maximum value is the last element
        System.out.println("Minimum value: " + min); // Output: 1
        System.out.println("Maximum value: " + max); // Output: 9
    }
}

In this example, we have an array numbers with values {5, 2, 8, 1, 9, 4}. We use the Arrays.sort() method to sort the array in ascending order.

After sorting, the minimum value will be the first element, accessed by numbers[0], and the maximum value will be the last element, accessed by numbers[numbers.length - 1].

Use the Stream Method To Get the Lowest and Largest Numbers

You can use the min() and max() methods given by the Stream API (application programming interface) to extract the lowest and highest values from a stream in Java, . These methods return an optional object that holds the lowest or maximum element in the stream, respectively. You can invoke the get() method on the optional object to receive the value. 

Example:

import java.util.Arrays;
public class main {
    public static void main(String[] args) {
        int[] numbers = {5, 2, 8, 1, 9, 4};
        // Find the minimum value
        int min = Arrays.stream(numbers).min().orElse(0);
        // Find the maximum value
        int max = Arrays.stream(numbers).max().orElse(0);
        System.out.println("Minimum value: " + min); // Output: 1
        System.out.println("Maximum value: " + max); // Output: 9
    }
}

In this example, we have an array numbers with values {5, 2, 8, 1, 9, 4}. We use the Arrays.stream() method to convert the array into a stream of integers. Then, we apply the min() and max() methods to find the minimum and maximum values, respectively.

The min() and max() methods return an OptionalInt object, representing an optional result. You can use the orElse() method to provide a default value if the stream is empty. In this example, we use orElse(0) to specify that if the stream is empty, the default minimum and maximum values should be 0.

Conclusion 

You must master Java array length handling strategies to construct successful and error-free software. The array length attribute will help you manage arrays efficiently, securely access their members, and prevent typical hazards like accessing out-of-bounds indices. You can sign up for a professional Java course at online learning platforms like upGrad to gain in-depth knowledge of fundamental and advanced Java programming concepts.

FAQs

1. What is the difference between length and length() in Java?

The size of an array is specified by the Java instance variable 'length'. In contrast, length() is a String class function that returns the number of characters in the string.

2. What is string length in Java?

In Java, the length() function is used to determine the length of a string. This function returns the number of 16-bit Unicode characters in the string.

3. How to determine Java list length?

You can determine the length of a Java list using the size() method on the list object in Java. The list's element count is returned by the size() function.

Leave a Reply

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