Skip to content
Advertisement

Will volatile variables in a class be set to 0 by default?

I know java will have a default constructor to initialize variables to 0, but how about volatile variables?

   class Test { 
       volatile long a;
       volatile double b;
       volatile int c;
    }

and I print them and every time result is 0, but is it guaranteed ?

Advertisement

Answer

The Java Language Specifiction, section 4.12.5, says:

Each class variable, instance variable, or array component is initialized with a default value when it is created:

  • 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.
  • For type int, the default value is zero, that is, 0.
  • For type long, the default value is zero, that is, 0L.
  • For type float, the default value is positive zero, that is, 0.0f.
  • For type double, the default value is positive zero, that is, 0.0d.
  • For type char, the default value is the null character, that is, ‘u0000’.
  • For type boolean, the default value is false.
  • For all reference types (ยง4.3), the default value is null.

As you can see, this rule applies to all fields, regardless of their volatility.

Advertisement