Java Array Length Examples

Java Array Length: 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.

Java Array Length Examples

Array Length Java

An array is a group of like-typed variables that are referred to by a common name. Arrays in Java work differently than they do in C/C++. The following are some important points about Java arrays.

  • In Java, all arrays are dynamically allocated. (discussed below)
  • Since arrays are objects in Java, we can find their length using member length. This is different from C/C++ where we find length using size.
  • A Java array variable can also be declared like other variables with [] after the data type.
  • The variables in the array are ordered and each has an index beginning from 0.
  • Java array can be also be used as a static field, a local variable or a method parameter.
  • The size of an array must be specified by an int value and not long or short.
  • The direct superclass of an array type is Object.
  • Every array type implements the interfaces Cloneable and java.io.Serializable.

The array can contain primitives data types as well as objects of a class depending on the definition of the array. In the case of primitives data types, the actual values are stored in contiguous memory locations. In case of objects of a class, the actual objects are stored in the heap segment.

Java Length Of Array

array length: length is a final variable applicable for arrays. With the help of the length variable, we can obtain the size of the array.
string.length() : length() method is a final variable which is applicable for string objects. length() method returns the number of characters present in the string.

length vs length()

  1. The length variable is applicable to the array but not for string objects whereas the length() method is applicable for string objects but not for arrays.
  2. Examples:
    // length can be used for int[], double[], String[] 
    // to know the length of the arrays.
    
    // length() can be used for String, StringBuilder, etc 
    // String class related Objects to know the length of the String
  3. To directly accesses a field member of the array we can use .length; whereas .length() invokes a method to access a field member.

Length Of An Array Java

Length Of An Array Java
Java Array Length Examples

Java Array Object does not have a method to get its length. From the Java Specification, an Array has a “public final length” field that contains the number of its components. The value can be a positive number or zero. Therefore, in order to get the Java Array Length, your code needs to access the array length attribute. Here is a simple example:

/**
 * A Simple Example to get the Java array length.
 */
public class JavaArrayLengthTest {
   public static void main(String[] args) {
      String[] testArray = { "Apple", "Banana", "Carrots" };
      int arrayLength = testArray.length;
      System.out.println("The length of the array is: " + arrayLength);
   }
}

Since the array has three elements, the expected output of the program will be:

The length of the array is: 3

From the code sample, the array length is retrieved from the array length attribute:

int arrayLength = testArray.length;

But often in our code, we need to process an array where we are not sure how the array object was created. Here is a sample code where we write a function that receives an array and prints the length of it.

Java Get Length Of Array

Java provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

Instead of declaring individual variables, such as number0, number1, …, and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and …, numbers[99] to represent individual variables.

This tutorial introduces how to declare array variables, create arrays, and process arrays using indexed variables.

Declaring Array Variables

To use an array in a program, you must declare a variable to reference the array, and you must specify the type of array the variable can reference. Here is the syntax for declaring an array variable −

Syntax

dataType[] arrayRefVar;   // preferred way.
or
dataType arrayRefVar[];  // works but not preferred way.

Note − The style dataType[] arrayRefVar is preferred. The style dataType arrayRefVar[] comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.

Example

The following code snippets are examples of this syntax −

double[] myList;   // preferred way.
or
double myList[];   // works but not preferred way.

Length Of Array In Java

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:

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

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.

Get Length Of Array Java

A Java array variable is declared just like you would declare a variable of the desired type, except you add [] after the type. Here is a simple Java array declaration example:

int[] intArray;

You can use a Java array as a field, static field, a local variable, or parameter, just like any other variable. An array is simply a variation of the data type. Instead of being a single variable of that type, it is a collection of variables of that type.

Here are a few more Java array declaration examples:

String[]  stringArray;

MyClass[] myClassArray;

The first line declares an array of String references. The second line declares an array of references to objects of the class MyClass, which symbolizes a class you have created yourself.

You actually have a choice about where to place the square brackets [] when you declare an array in Java. The first location you have already seen. That is behind the name of the data type (e.g. String[]). The second location is after the variable name. The following Java array declarations are actually all valid:

int[] intArray;
int   intArray[];

String[] stringArray;
String   stringArray[];

MyClass[] myClassArray;
MyClass   myClassArray[];

Personally I prefer to locate the square brackets [] after the data type (e.g. String[]) and not after the variable name. After all, an array is a special kind of data type, so I feel it is easier to read the code when the square brackets are placed right after the data type in the array declaration.

When you declare a Java array variable you only declare the variable (reference) to the array itself. The declaration does not actually create an array. You create an array like this:

int[] intArray; intArray = new int[10];

This example creates an array of type int with space for 10 int variables inside.

The previous Java array example created an array of int which is a primitive data type. You can also create an array of object references. For instance:

String[] stringArray = new String[10];

Java allows you to create an array of references to any type of object (to instances of any class).

Java Array Literals

The Java programming language contains a shortcut for instantiating arrays of primitive types and strings. If you already know what values to insert into the array, you can use an array literal. Here is how an array literal looks in Java code:

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

Notice how the values to be inserted into the array are listed inside the { ... } block. The length of this list also determines the length of the created array.

Actually, you don’t have to write the new int[] part in the latest versions of Java. You can just write:

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

It is the part inside the curly brackets that is called an array literal.

This style works for arrays of all primitive types, as well as arrays of strings. Here is a string array example:

String[] strings = {“one”, “two”, “three”};

Java Array Length Cannot Be Changed

Once an array has been created its size cannot be resized. In some programming languages (e.g. JavaScript) arrays can change their size after creation, but in Java, an array cannot change its size once it is created. If you need an array-like data structure that can change its size, you should use a List, or you can create a resizable Java array. In some cases, you can also use a Java RingBuffer which, by the way, is implemented using a Java array internally.

How do you find the length of an array in Java?

  1. public class JavaStringArrayLengthExample {
  2. public static void main(String args[]){
  3. String[] strArray = new String[]{“Java”, “String”, “Array”, “Length”};
  4. int length = strArray. length;
  5. System. out. println(“String array length is: ” + length);
  6. for(int i=0; i < length; i++){
  7. System. out. println(strArray[i]);

How do you find the size of an array?

To determine the number of elements in the array, we can divide the total size of the array by the size of the array element. You could do this with the type, like this: int a[17]; size_t n = sizeof(a) / sizeof(int);

What is the difference between the length of an array and the size of ArrayList?

ArrayList doesn’t have length() method, the size() method of ArrayList provides the number of objects available in the collection. The array has length property which provides the length or capacity of the Array. It is the total space allocated during the initialization of the array.