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

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

    It's really depends what you're doing in your program.

    "" (empty string) is connected only with String and it's safer than null. When you call methods from String class for example: replaceAll(), indexOf() the program will work correctly but when you have null, you have NullPointerException all time when you're calling method on it.

    Consider if string empty value in your application is not something bad to you, then choose str="".

    Notice that very often is better when NullPointerException is thrown because we know about an invalid state in our application, so when you want know about this set String to null by default.

提交回复
热议问题