Core Java

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.

Published on Java Code Geeks with permission by Alex Theedom, partner at our JCG program. See the original article here: Inline array definition in Java

Opinions expressed by Java Code Geeks contributors are their own.

Alex Theedom

Alex Theedom is a Senior Java Developer and has recently played a pivotal role in the architectural design and development of a microservice based, custom built lottery and instant win game platform. Alex has experience of Java web application development in a diverse range of fields including finance, e-learning, lottery and software development. He is the co-author of Professional Java EE Design Patterns and many articles.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Newest Most Voted
Inline Feedbacks
View all comments
Back to top button