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
.
The method does a lot of appending
do you refer tomethod1
or actually the code your showing? I can get thatmethod1
does a lot of appending and could need anStringBuilder
, but in the code your showing I don't see anyString
manipulation only asb.toString
(which should besb.toString()
) – Marc-Andre May 20 '14 at 19:40method1
…method4
make this hypothetical code, which is off-topic for Code Review. Please ask a follow-up question with real or realistic details. – 200_success♦ May 20 '14 at 19:47