Skip to content
Advertisement

How to return a boolean from a function in java? getting an error

public class Test {
    public boolean checkx(boolean x) {
        boolean status;
        if (x) {
            status = true;
        }
        return status;
    }
}

Error: The local variable status may not have been initialized

I don’t know what I was doing wrong, code looks alright to me.

Advertisement

Answer

In the Java Language Speciication, it is written that:

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).

So, you must have to initialize or assign a value to the local variable before using it.

In your particular example:

public boolean checkx(boolean x) {
    boolean status = false;
    if (x) {
        status = true;
    }
    return status;
}
Advertisement