Should Java String method (local) variables be initialized to null or “”?

前端 未结 6 1831
攒了一身酷
攒了一身酷 2021-02-13 16:55

What is the best practice for initializing a String method (local) variable to avoid the \"Variable might not have been initialized\" error in Java?

String s=null; or St

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-13 17:45

    Yes, it makes a difference. One is a reference to an empty string, one is a null reference. They're not the same.

    Which is better? It depends whether you want a null value or a reference to an empty string... they behave differently, so pick the one which behaves the way you want it to.

    I rarely need to assign a "dummy" value to a variable though - usually just initializing the variable at the point of declaration with the real value I want is fine. If you can give us more context, we may be able to help you structure your code better so this isn't a problem for you.

提交回复
热议问题