Java Array Length vs. Size
A Programmer’s Life
Programming in any language has its complexities. You need to understand the nuances of the target system, and you need to come up with a design that effectively solves the problem at hand. And, you need to do both under a tight schedule. This shouldn’t come as any real surprise. Each language brings its own uniqueness to the table. These are those little quirks and efficiencies that separate it from the rest. Java is no different in that respect. And, like all languages, there are certain syntactic constructs that make programming easier. One of those is the array.
What Is a Java Array?
A Java array is an ordered collection of elements. Arrays can be created using virtually any type of information. But once the type is selected, all elements in the array will be of that type. They are said to be homogeneous. For example, a five-element array of integers might be declared as follows:
- int[] test = new int [5];
This declaration creates a new array called ‘test.’ This array consists of five elements. Each element is accessed using its position in the array, also called its index. Java arrays start at zero and are numbered up sequentially from there. For this array, the indexes would be 0, 1, 2, 3, and 4.
Length of a Java Array
The length of a Java array is the number of elements in the array. So, in our integer array example, the length is five. Here is another array declaration:
- int[] test2 = new int [7];
The length, in this case, is seven. It is important to note that arrays are fixed in Java. Once declared, the length cannot be changed. In other words, for the above examples, the lengths will always be five and seven respectively. To find the length of an array, you would use the following:
- int len = test2.length;
This places the value seven in the variable ‘len.’