Skip to content

Java Array Length Method and Examples

  • by

Finding a Java Array Length is very easy, just use the length final variable (length() method is different). In Array, the length property always shows the int value of the total allocated space in the initialization.

First, learn about array with this tutorial if you are a beginner or not know about Array: Java Array complete tutorial

Java Array Length Is Methods? How to get Array length

Syntax:

A simple syntax of length method in java.

numbers.length;

Return value: int size of the array.

Java array length example

A Simple example created an integer array then created an int varible “size”. Storing the array length result in size then print the output.

class Hello {
    public static void main(String[] args) {

        int[] numbers = {5, 2, 5, 2, 9};
        int size = numbers.length;

        System.out.println(size);

    }
}

Output: 5

Q: How to find the length of integer array in java?

Answer: As the same above examples use the length property in Array. When the array is created and initialized, if declaring an Array size. It will be the size or length of the Array in Java.

class Hello {
    public static void main(String[] args) {

        //Creating a array 
        int[] numbers = new int[10];
        System.out.println("Array Size is " + numbers.length);
    }
}

Output: Array Size is 10

Q: Difference between length and length() in Java?

Answer: As mentioned in the starting a length is not a method it returns the only length of Array it will not work on objects. Or you can also call length is a property.

Another length() is methods returns the number of characters presents in the string object.

length – to know the length of the Arrays (int[], double[], String[]).

length() – to know the length of the String related Object (String, StringBuilder, etc).

With this example, you will get more clarity.

class Hello {
    public static void main(String[] args) {

        //length
        int[] numbers = {5, 2, 5, 2, 9};
        System.out.println("Array Size is " + numbers.length);

        // length()
        String str = "EyeHunts";
        System.out.println("String Size is " + str.length());

    }
}

Output: Array Size is 5
String Size is 8

Calling Java Array Length function or method both are same. Java array length can’t change after initialization.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1

Java version 11

All Java Array Length Examples are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.

Leave a Reply

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