How do I better structure Java code to avoid dereferencing null?
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.