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?
-
2[Difference between null and empty (“”) Java String](http://stackoverflow.com/questions/4802015/difference-between-null-and-empty-java-string) – ifly6 Feb 22 '16 at 08:43
-
Well, you can only assign `0` to a primitive numeric or boxed primitive numeric type. You can only assign `""` to a string reference. You can assign any object reference to `null`. – Andy Turner Feb 22 '16 at 08:48
3 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 = "";

- 15,053
- 14
- 60
- 75
for declaring a string you can use "".
for declaring any other non primitive data type you can use null (be careful about null pointer exception).
for numeric data type like byte
, int
use can use 0.

- 692
- 7
- 25
-
You *can* assign a String the initial value `""`, but this value is completely different to giving it the value `null`. Perhaps you can expand upon the difference. – Andy Turner Feb 22 '16 at 08:49
Null
- This can be assigned to all non-primitives type (just to indicate that this is not referring to any object, and can throw null pointer)
" "
- Only for String Literal
Zero can be assigned to all the primitives and Numeric Wrappers /Boxed Primitives
char zeroChar = 0;
float zeroFloat = 0;
double zeroDouble = 0;
short zeroShort = 0;
long zeroLong = 0;
byte zeroByte = 0;
int zeroInt = 0;

- 378
- 7
- 21