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

前端 未结 6 1813
攒了一身酷
攒了一身酷 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:34

    Best practice is to make as many fields final as possible or use default values to avoid clients instantiating bad or incomplete objects. If it makes sense for the field to be an empty string by default (i.e. it will not risk logic errors) then by all means do it that way. Otherwise, at least null will throw an exception when a client invokes a method on an object that hasn't been properly instantiated.

    So in general, try to force client code to create complete objects during construction. If you don't know what the string should be at construction time, then have them pass it in as a parameter. If the string is just used for internal logic, it may be better as a local variable or parameter - and in that case I generally prefer null to "" because == null is more explicit than isEmpty().

提交回复
热议问题