Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
1D Array Length
Java Basics Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Java Basics Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
-->
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
As we stated previously, the way index works with arrays is similar to how index works with String values. Arrays also have a way of returning their own length, but in place of a method like with strings, the array's length is a variable, meaning the parenthesis are not needed. Look below to see how we can access the length of an array.
ArrayLength1DExample.java
package exlcode;
public class ArrayLength1DExample {
public static int[] exampleVariableOne = new int[5];
public static int[] exampleVariableTwo = {0, 1, 2, 3, 4, 5, 6, 7, 8};
// returns the length of the array and assigns
// it to integer variables
public static int lengthOne = exampleVariableOne.length;
public static int lengthTwo = exampleVariableTwo.length;
public static void main(String[] args) {
System.out.println(lengthOne);
System.out.println(lengthTwo);
}
}
The length of an array equals the number of elements it can hold. The last index of an array is array.length-1. Remember that the length() method in the String class works differently than array.length().
The length of an array cannot be altered after it is initialized. Please remember this quality when you loop through arrays with for/while statements.