Search code examples
javaarraysinitializationconditional-operator

Array initialization with ternary operator in Java


Why will Java let me initialize an array like this: int[] anotherArray = {1,2,3,4,5};

But won't accept this: int[] anArray = (arr.length > 0) ? {1,2,3,4,5}: {};

Image


Solution

  • To make your code work, do the following instead:

    int[] anArray = (arr.length > 0) ? new int[]{1,2,3,4,5}: new int[]{};
    

    To understand why the original code didn't work, we need to understand two things: 1) the ternary operator, and 2) the ways to initialize an array.

    1. The ternary operator (?:)

    The ...?...:... expression is called the ternary operator (not lambda). It is simply a shorthand for an if-else statement. You can find out more about the ternary operator in the Oracle tutorial.

    Another conditional operator is ?:, which can be thought of as shorthand for an if-then-else statement

    2. Ways to initialize arrays in Java

    int[] anArray = {1,2,3,4,5} (without new) is a shorthand for instantiating an array, and can only be used when initializing the array during declaration. When an array is instantiated outside of declaration, the new operator must be used ("new int[]{...}"). For example:

    int[] b = new int[] {1, 2, 3} // ok
    int[] c = {1, 2, 3} // ok
    
    int[] arr;
    arr = new int[]{1, 2, 3} // ok
    arr = {1, 2, 3} // compilation error
    

    More about array creation in the section "Creating, Initializing, and Accessing an Array" in the Oracle tutorial here.

    Why the original code didn't work

    Putting the above pieces of information together, 1) ?: is simply another way of writing an if-else statement, and 2) when instantiating an array outside of declaration the new operator is required. Your original statement is equivalent to the following:

    int[] anArray;
    if (arr.length > 0) {
        anArray = {1,2,3,4,5} // compilation error
    } else {
        anArray = {}; // compilation error
    }
    

    To fix the compilation error, the new operator should be used:

    int[] anArray;
    if (arr.length > 0) {
        anArray = new int[]{1,2,3,4,5} // ok
    } else {
        anArray = new int[]{}; // ok
    }
    

    Which then simplifies to:

    int[] anArray = (arr.length > 0) ? new int[]{1,2,3,4,5}: new int[]{};