Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default values and initialization in Java

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?

like image 766
Michael 'Maik' Ardan Avatar asked Oct 02 '13 06:10

Michael 'Maik' Ardan


People also ask

What is default initialization in Java?

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.

Which variables are initialized with default values in Java?

In Java, the default initialization is applicable for only instance variable of class member.

What is default initial value?

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.


1 Answers

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.

like image 161
Juned Ahsan Avatar answered Oct 01 '22 17:10

Juned Ahsan