From what I know, initalizing a variable is when you set a value to it. For example:
String s; // declaring the String (throws an error if you use in conditionals)
String s = null; // declaring and then initializing the String (no error)
However, when a String
is declared, isn't it automatically initialized to null
? Therefore, the compiler shouldn't throw an error.
I also noticed that String s = new String();
does not produce any errors when used with conditionals but String s;
does. I thought these two statements were essentially the same thing and the latter was even encouraged over the former.
My questions are, why does String s = new String();
work but not String s;
(when using conditionals to set their value)? Shouldn't both strings be automatically initalized to null
, therefore not causing an error?
Bonus question: Since String
objects are automatically initialized to null
, why does the following code print an empty String
?
String s = new String();
System.out.println(s);
EDIT: Apparently I don't think straight when I'm tired. This whole question is a mess, I have no idea what I was thinking. Apologies to those who had to try and understand it.
Also, the Oracle docson default values:
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.
Which answers the above question.