Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Three argument operator: Local variable may not have been initialized

I have the following piece of code...

import java.util.Random;

public class ThreeArgumentOperator {

    private static final Random RANDOM = new Random();

    public static void main(String[] args) {
        String test;
        System.out.println(test = getValue() == null ? "" : test);
    }

    public static String getValue() {
        if (RANDOM.nextBoolean()) {
            return "";
        } else {
            return null;
        }
    }

}

The Eclipse compiler (I am using Juno) reports the following error:

The local variable test may not have been initialized

My question is: Should not the compiler report in this case that it rather cannot convert boolean to String? I understand that the operator == takes precedence over = and therefore the compiler should complain about the casting, instead it complains about possibly not initialized value.

When I change the following line

System.out.println(test = getValue() == null ? "" : test);

to

System.out.println((test = getValue()) == null ? "" : test);

everything works fine.

EDIT: I have also tried to compile it using javac directly. It gives the same error.

error: variable test might not have been initialized
System.out.println(test = getValue() == null ? "" : test);
like image 508
Jagger Avatar asked Mar 28 '26 05:03

Jagger


1 Answers

The error the compiler is providing you is correct. According to the operator precedence, == will be evaluated first, then your ternary operator ? :. That means, the flow of logic is as follows:

getValue() == null

In order to continue, let's assume the result of this was false. The next expression that follows:

false ? "" : test

The result of this then is test. And our final expression...

test = test

But test was never initialized, hence the error.

like image 153
cklab Avatar answered Mar 29 '26 18:03

cklab