Matt
Matt

Reputation: 71

Why is java saying I haven't initialized variable?

The following code is giving me an error pointing at the 'm' in the statement "return mon;". It states "variable mon might not have been initialized" when it is very clearly initialized at the beginning of this method. it's gotta be something super simple, I just don't understand! Thank you.

public String monthName(int month)
{
    String mon;
    switch (month)
    {
        case 1:
            mon = "January";
            break;
        case 2:
            mon = "February";
            break;
        case 3:
            mon = "March";
            break;
        case 4:
            mon = "April";
            break;
        case 5:
            mon = "May";
            break;
        case 6:
            mon = "June";
            break;
        case 7:
            mon = "July";
            break;
        case 8:
            mon = "August";
            break;
        case 9:
            mon = "September";
            break;
        case 10:
            mon = "October";
            break;
        case 11:
            mon = "November";
            break;
        case 12:
            mon = "December";
            break;
    }
    return mon;
}

Upvotes: 1

Views: 193

Answers (3)

Chris Harlow
Chris Harlow

Reputation: 61

Returning null if the month number is incorrect is only any good if the caller expects that to happen and is prepared to check for null.

If the calling routine is not going to check for a null return, then you should throw a RuntimeException in the default case. This is much better than allowing the code to fail some time later with a null pointer exception caused by a bad month name!

For example..

default:
  throw new RuntimeException("Invalid month number "+ month);

This will also stop the compiler complaining because there is no way to get to the return statement with mon not initialised.

Upvotes: 0

Piyas De
Piyas De

Reputation: 1764

You should have a default case for mon variable assignment in switch (month). Also you should assign null value to it.

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198014

Who is to say that month is always an integer between 1 and 12? The compiler certainly can't guarantee it.

Either initialize mon to null, or set behavior in the default case in your switch. (Also, you can just return the month names directly instead of setting them in a temporary variable.)

Alternately, a simpler solution might be

String[] monthNames = {"January", "February", ..., "December"};
return monthNames[month - 1];

Upvotes: 12

Related Questions