Home > front end >  Java - Uninitialized final variable of an Enum can be assigned without producing error?
Java - Uninitialized final variable of an Enum can be assigned without producing error?

Time:09-22

So I was cleaning my code and adding final keywords to whichever places possible, one of those place happen to be an uninitialized variable of enum type.

The variable is not initialized because its value needs to be determined by a switch statement. It would not make sense to make this variable final in this case but I did it anyways by accident, and found out that the code works fine without producing any error.

With my understanding, an uninitialized variable in Java will hold default value (which in this case I think should be null), and a final variable cannot be re-assigned to a different object.

How come this code does not produce any error nor side effect?


Notes:

  • NeighborPosition is an enum type

final NeighborPosition edgePosition;
switch(cornerPosition) {
    case ONE:
        edgePosition = NeighborPosition.THREE;
        break;
    case TWO:
        edgePosition = NeighborPosition.FOUR;
        break;
    case THREE:
        edgePosition = NeighborPosition.FIVE;
        break;
    case FOUR:
        edgePosition = NeighborPosition.SIX;
        break;
    case FIVE:
        edgePosition = NeighborPosition.ONE;
        break;
    case SIX:
        edgePosition = NeighborPosition.TWO;
        break;

    case ZERO:
    default: {
        throw new IllegalStateException(
            "Should never reach this corner, current corner: "
              cornerPosition);
    }
}

CodePudding user response:

Local variable are not initialized by default, only fields are.

In all possible cases, your code will either assign a value to edgePosition or throw an exception (in which case, the local variable gets out of scope).

  • Related