0

The Java Tutorial website writes: "It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style."

But if I write something like

int i;
System.out.println(i);

I get a compile-time exception: variable i might not have been initialized

So what does it mean for a data type like int to have a default value if it doesn't mean an automatic assignment of the variable to the default value (0)?

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

  • 5
    Note that that documentation link literally explains this: "_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_". – Mike 'Pomax' Kamermans Jan 05 '22 at 18:57
  • Thanks @Mike'Pomax'Kamermans – Philipp Crosman Jan 05 '22 at 19:01

0 Answers0