Why does initializing a string in an if statement seem different than in a switch statement?
That is because you did not specify what season has to be in the default case. What happens when month is not within 1-12? season
will not be initialized.
If you are expecting strictly only 1-12 as month input, then you might want to consider throwing an Exception
in default:
default:
throw new IllegalArgumentException("Invalid month");
In your first example, there is no path through the code that fails to assign a value to 'season'. In the second example, the default case does not assign a value, so the last print ("May is...") can be executed with an uninitialized value.
In your if
/else
code, there is an assurance that the variable season
will get a value. That is, the else
statement.
Your switch
code does not have it. Look what will happen to the variable season
if the given value for month is 13
-- it will not get a value, and will remain un-initialised.