Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

java - Why do I get a "variable might not have been initialized" compiler error in my switch block?

I'm encountering "a variable might not have been initialized" error when using switch block.

Here is my code:

public static void foo(int month)
{
    String monthString;
    switch (month)
    {
        case 1: monthString = "January";
                break;
        case 2: monthString = "February";
                break;
    }
    System.out.println(monthString);
}

The error:

Switch.java:17: error: variable monthString might not have been initialized
        System.out.println (monthString);

To my knowledge this error occurs when you try access a variable you have not initialized, but am I not initializing it when I assign it the value in the switch block?

Similarly, even if the month is a compile-time constant, I still receive the same error:

public static void foo()
{
    int month = 2;
    String monthString;
    switch (month)
    {
        case 1: monthString = "January";
                break;
        case 2: monthString = "February";
                break;
    }
    System.out.println(monthString);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If month isn't 1 or 2 then there is no statement in the execution path that initializes monthString before it's referenced. The compiler won't assume that the month variable retains its 2 value, even if month is final.

The JLS, Chapter 16, talks about "definite assignment" and the conditions under which a variable may be "definitely assigned" before it's referenced.

Except for the special treatment of the conditional boolean operators &&, ||, and ? : and of boolean-valued constant expressions, the values of expressions are not taken into account in the flow analysis.

The variable monthString is not definitely assigned prior to being referenced.

Initialize it before the switch block.

String monthString = "unrecognized month";

Or initialize it in a default case in the switch statement.

default:
    monthString = "unrecognized month";

Or throw an exception

default:
    throw new RuntimeExpception("unrecognized month " + month);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...