Java Arrays, Wat!

Java Arrays: Surprising Behaviors

Arrays in Java can behave in unexpected ways. Let's explore a few quirks.

Is it an Array or Not?

Consider the following declaration:

Serializable array = new Serializable[9];

Is array an array or a scalar? In fact, it’s a scalar reference that points to an array. Similarly:

Object o = new Object[9];

Here, you can assign an array to an Object variable because arrays are also objects in Java. Additionally, arrays are Serializable, so they can be assigned to a Serializable reference as well.

Where Did My [] Go?

Java syntax can produce some surprising results due to backward compatibility. Consider this method signature:

public static int method(int[]... args)[] {
    return args[0];
}

In this example:

  • args is of type int[][].
  • The return type is int[], indicated by the [] after the method declaration.

This syntax isn’t part of the Java Language Specification (JLS); it’s allowed in OpenJDK for backward compatibility.

What's the Difference Between int[] array and int array[]?

There is a subtle difference when additional brackets follow:

int[] array, x[];

and

int array[], y[];

In these cases:

  • x is of type int[][].
  • y is of type int[].

What Happens If an Array Initialization is Too Large?

Consider initializing a large array like this:

public static final int[] VALUES = {
    1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
    /* many, many lines deleted */
    1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
};

This produces an error:

Error:(6, 31) java: code too large

It may seem odd that the error is not about the array size but rather the code size. This is because arrays are initialized in bytecode, which generates code to create and populate the array one element at a time. When the array is large, the generated bytecode exceeds Java's method size limit (65,535 bytes).

Due to this limit, large initialized arrays or a high number of enum values may result in compilation errors.

The Code

Code to run the examples that compile above are here JavaArraySurprises.java

Comments

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

Comparing Approaches to Durability in Low Latency Messaging Queues