-3

I'm setting up a method to convert int month input by user into String, but can't seem to return the String.

Error shows

Variable monthString might not have been initialized

public String StringMonth()
    {
       String monthString;
       switch (month)
    {
        case 1: monthString = "January";
        break;
        case 2: monthString = "February";
        break;
        case 3: monthString = "March";
        break;
        case 4: monthString = "April";
        break;
        case 5: monthString = "May";
        break;
        case 6: monthString = "June";
        break;
        case 7: monthString = "July";
        break;
        case 8: monthString = "August";
        break;
        case 9: monthString = "September";
        break;
        case 10: monthString = "October";
        break;
        case 11: monthString = "November";
        break;
        case 12: monthString = "December";
        break;
    }
       return monthString;
    }
}
Butiri Dan
  • 1,759
  • 5
  • 12
  • 18
  • Well, initialize it with a value. – Progman Jun 14 '19 at 20:34
  • 1
    There is a trace through your program where `monthString` is still not initialized, namely the **default case**, i.e. if none of the cases matched. Either provide a default-case or initialize it right away. Since the default case should in practice never trigger, do `default : throw new AssertionError();` or a different error/exception, depending on your use-case. – Zabuzard Jun 14 '19 at 20:36

2 Answers2

2

This would do the trick:

public String StringMonth()
{
   String monthString = null;
   switch (month)
...

You may also wish to have a default case. And consider error handling when assigning a default value; what should happen?

Will
  • 6,601
  • 3
  • 31
  • 42
1

To fix simply do String monthString = null; or even better do String monthString = StringUtils.EMPTY;

Initializing a variable means assigning a variable an initial value before it ever gets used. If the variable has been declared but not Initialized then you will get the error message:

Variable ***** might not have been initialized

So in your case you are getting this error because you just have String monthString, and you don't initialize monthString with an initial value resulting in the error message.

I prefer String monthString = StringUtils.EMPTY over String monthString = null just because we are assigning it an actual string value and not just null.

This is an interesting topic about is StringUtils.EMPTY recommended albeit, it goes against what I'm suggesting about using StringUtils.EMPTY but I believe this makes it clear (that's just my opinion, not saying I'm right).

Popeye
  • 11,839
  • 9
  • 58
  • 91