News Ticker

Inline array definition in Java

There are occasion when it is more convenient to create an array inline. Here are several way to declare and initialise primitive arrays and java.util.Lists type arrays.

Declare a primitive array

Primitive data types are the following: byte, short, int, long, float, double, boolean and char. Arrays of any of these types can be easily declared and initialised.

int[] integers = new int[] { 1, 2, 3, 4, 5 };

Declare an array of Objects

An array of objects can be declared and initialised in the same way as shown above for primitive arrays.

String[] pets = new String[] { "cat", "dog", "fish" };

Custom objects can also form arrays.

class Cat {
  private String name;
  Cat(String name){ = name;

Cat[] cats = new Cat[] { 
 new Cat("Macavity"), 
 new Cat("Jennyanydots") 

Declare a List inline

The collections framework provides a healthy selection of List types that can be declared and initialised inline.

List pets = Arrays.asList(new String[] { "cat", "dog", "fish" });

Declare and use a primitive array inline

Arrays are used in iterations constructs such as the for-each construction. For convenience arrays can be declared and initialised inline in the for loop itself.

for (int i : new int[] { 1, 2, 3, 4, 5 }) {}

Declare and use an object array inline

Object arrays can also be declared and initialised inline in the for loop construct.

for (String pet : new String[] { "cat", "dog", "fish" }) {}

Final thoughts

The best practice is to declare and initialised the array separately from the location where you use it. The code snippets in this blog post show how to declare, initialise and use arrays inline for the purpose of building simple code examples.

I often use this construction approach when demonstrating java features and writing simple examples for new features.

1 Trackback / Pingback

  1. Constrast DataWeave and Java mapping operations

Leave a Reply