Damhan Richardson Damhan Richardson - 1 year ago 113
Java Question

variable might not have been initialized when using switch block?

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

Here is my code;

class Switch
public static void main (String [] args)
int month = 2;
String monthString;
switch (month)

case 1: monthString = "January";
case 2: monthString = "February";
case 3: monthString = "March";

System.out.println (monthString);



The error;

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

now 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??


Answer Source

If month isn't 1, 2, or 3, 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.

    monthString = "unrecognized month";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download