Java: “Local variable may not have been initialized” not intelligent enough?

前端 未结 3 1948
醉酒成梦
醉酒成梦 2020-12-17 03:49

Consider the following method:

void a ()
{
    int x;
    boolean b = false;
    if (Math.random() < 0.5)
    {
        x = 0;
        b = true;
    }
            


        
3条回答
  •  半阙折子戏
    2020-12-17 04:11

    No, there is no way Java can examine all possible code paths for a program to determine if a variable has been initialized or not, so it takes the safe route and warns you.

    So no, you will have to initialize your variable to get rid of this.

提交回复
热议问题