Based on my reference, primitive types have default values and Objects are null. I tested a piece of code.
public class Main { public static void main(String[] args) { int a; System.out.println(a); } }
The line System.out.println(a);
will be an error pointing at the variable a
that says variable a might not have been initialized
whereas in the given reference, integer
will have 0
as a default value. However, with the given code below, it will actually print 0
.
public class Main { static int a; public static void main(String[] args) { System.out.println(a); } }
What could possibly go wrong with the first code? Do class variables behave different from local variables?
From Java Language Specification. Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10): For type byte, the default value is zero, that is, the value of (byte)0. For type short, the default value is zero, that is, the value of (short)0.
In Java, the default initialization is applicable for only instance variable of class member.
The initial value of a CSS property is its default value, as listed in its definition table in the specification. The usage of the initial value depends on whether a property is inherited or not: For inherited properties, the initial value is used on the root element only, as long as no specified value is supplied.
In the first code sample, a
is a main
method local variable. Method local variables need to be initialized before using them.
In the second code sample, a
is class member variable, hence it will be initialized to the default value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With