0

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.

null
  • 2,060
  • 3
  • 23
  • 42
  • 2
    Your question is no different from others. A String is initialized to `null` **if** it is declared in the class. And `new String()` creates a String object as you would expect, not null. Nothing unusual to see here. – Hovercraft Full Of Eels Oct 08 '14 at 21:21
  • String s = new String(); is equivalent to String s = new String(""); so s is not null in the first case. – ToYonos Oct 08 '14 at 21:25
  • 1
    Voting to close with just one of many duplicates of this question. The "bonus" question is a non-question and doesn't need a duplicate as it is answered in any intro to Java book first chapter. – Hovercraft Full Of Eels Oct 08 '14 at 21:28
  • @HovercraftFullOfEels Apparently I don't think straight when I'm tired. Apologies for the duplicate/stupid questions. – null Oct 08 '14 at 21:34

1 Answers1

5

However, when a String is declared, isn't it automatically initialized to null? Therefore, the compiler shouldn't throw an error.

No, this is only true for class level variables. Local variables are not assigned a default value, but needs to be explicitly initialized.

Since String objects are automatically initialized to null, why does the following code print an empty String?

String objects are never initialized to null. Class level String references on the other hand, are.

Keppil
  • 45,603
  • 8
  • 97
  • 119