How do I better structure Java code to avoid dereferencing null? I have the situation where as long as the user gives valid input, the StringBuilder object will not be null.

StringBuilder sb = null;
switch(userInput)
{
  case 1:
    sb = method1();
    break;
case 2:
    sb = method2();
    break;
case 3:
    sb = method3();
    break;
case 4:
    sb = method4();
    break;
default:
    System.out.println("invalid input"); 
}

System.out.println(sb.toString);//gives warning "dereferncing possible null pointer


Update: for those commenting it should be String instead of StringBuilder could you please explain? The method does a lot of appending so it needs to use String. Why would you bother converting to String if you can directly print out a StringBuilder? It seems like there's an implicit belief that a StringBuilder should always be converted to a String.
You need to ensure that every statement in the switch is one that ensures that sb != null holds, this is not the case currently.

You can fix this by throwing an exception instead of logging a message, like this:

default:
    throw new IllegalArgumentException("input was invalid: " + userInput);


I also included that it tells you what the actual input was.

Other remarks are that your code has syntax errors, making it borderline ontopic, and your coding style definately needs improvement, I propose the following hence:

StringBuilder sb = null;
switch (userInput) {
    case 1:
        sb = method1();
        break;
    case 2:
        sb = method2();
        break;
    case 3:
        sb = method3();
        break;
    case 4:
        sb = method4();
        break;
    default:
        throw new IllegalArgumentException("input was invalid: " + userInput);
}

System.out.println(sb.toString());


Furthermore it seems very odd to me that your methods return a StringBuilder. I would just work with Strings here, as you are not doing an extensive amount of string concatenation.

Short guide:


String, to be used for regular text.
StringBuilder, to be used when you need to concentate/append a lot of strings.
StringBuffer, similar to StringBuilder, but now add to that that you are working in a multithreaded environment, hence you will almost never need this.