Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between initializing variables with null or 0 or "" [closed]

Could anyone provide simple example when and where to declare null or 0 or "" while declaring variables in java? I went through some examples but didn't understand, so can anyone explain clearly with some simple examples?

like image 721
kumar Avatar asked Mar 23 '26 21:03

kumar


1 Answers

  • Class variables, instance variables, or array components are initialized for you (non-final ones), so there is no need to initialize them to false/null/0 (it will be redundant):

    Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):

  • You need to initialize local variables though:

    Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

  • If you want an empty string for instance, use String myStr = "";
like image 94
Idos Avatar answered Mar 26 '26 10:03

Idos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!