0

Java strings are initialized to null if you don't set them to a value:

String str;

The value of the above string is null.

I see in code online people doing the following:

String str = null;

But isn't that redundant since it is set to null anyway? What is the best practice for initializing a string?

  • 5
    I always set it to null myself. It's a habit, but also helps that I do this everywhere and don't get `variable not initialized` errors. – tima Aug 24 '17 at 15:50
  • The first options are better. All variables objects by default is null so the second is redundant – Onregs Aug 24 '17 at 15:51
  • 1
    @Onregs not all variables are set to null by default. Refer to the duplicate question's answer. – tima Aug 24 '17 at 15:54
  • Local variables must be initialised to null, they will not be initialised automatically. No, it is not always redundant. You shouldn't initialise field variables though, they will be initialised automatically. – Killer Death Aug 24 '17 at 15:55
  • @tima can you give me example pls? I think you mean primitives but objects are always null – Onregs Aug 24 '17 at 16:00
  • @tima definite assignment analysis is there to help you make sure that you've assigned the value you need to assign before you use it - unless you actually need to assign null, you may end up forgetting to reassign the correct value in some logical branch, and then you end up with a NPE. You're just disregarding free help from the compiler. – Andy Turner Aug 24 '17 at 16:00
  • @AndyTurner like I said, it's a habit, I can't change now :) – tima Aug 24 '17 at 16:03

0 Answers0