Creating an Inline Array in Java

The usual way of creating an array in Java is given below. In this example, we create a String array containing primary color names,

public class InlineArrays {

    public static void main(String[] args) {
        String[] colors = {"red","green","blue"};
        printColors(colors);
    }
    public static void printColors(String[] colors) {
        for (String c : colors) {
            System.out.println(c);
        }
                
    }
}

The problem with this approach is that it is unnecessarily verbose. Also there is no need to create a temporary array variable to pass a constant list of values.

Java also provides an inline form of array creation which doesn’t need a temporary variable to be created. You can use the inline array form directly as a parameter to a method. Here is the above code example written using inline Java arrays,

public class InlineArrays {

    public static void main(String[] args) {
        printColors(new String[]{"red","green","blue"} );
    }
    public static void printColors(String[] colors) {
        for (String c : colors) {
            System.out.println(c);
        }
                
    }
}

Still the above usage is not as concise as we want it to be. Alternatively you can also use the Varargs feature introduced in Java 5. Whenever Varargs is used, the successive arguments to the method is automatically converted to array members. This is the most concise way of creating an array inline! The above code example can be written as follows,

public class InlineArrays {

    public static void main(String[] args) {
        printColors("red","green","blue");
    }
    public static void printColors(String... colors) {
        for (String c : colors) {
            System.out.println(c);
        }
    }
}

Note the use of … immediately after the String type in printColors() method definition. This instructs the compiler to automatically convert one or more String arguments into array members of the variable colors. Inside the method you can treat colors as an array.

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution on this site within 48 hours! Please email us.


Leave a Reply