String str1;
String str2 = null;
String str3 = "";
String str4 = new String();
String str5 = new String("");
I know that for 3rd initialization above, the the string object is initialized in the string pool and the 4th has nothing to do with the string pool.
What is the difference between 1. and 2.? If I consider str1
as a pointer variable, what it stores is a particular memory address that is never used by the JVM or OS?
Is there a difference between 4. and 5.?
When I print str1
and str2
directly by System.out.println(str1)
and System.out.println(str2)
, for str1
, I can't even pass the compilation.For str2
, compilation is OK and I get "null" and the output in the console window. Why?
Edited after the answer of @aioobe: more questions:
I would like to know more about "null". Since str2
(reference variable) is like a pointer variable, there should be something (0/1 bits) in it (in the memory occupied by this pointer variable). As it is initialized as null, is it all-0-bits or the bytecode of null is all-zero? Another question is that if I call the method toString() on str2
by str2.toString()
, I got a NullPointer Error at runtime. So it is JVM that checks if the reference variable is null? How can JVM know that it is null? JVM checks the bits in str2
?
One more question about null in Java: concatenation of null and a string literal