Final static variables

18 January 2012 By Nithya Vasudevan 403 views No Comment
0 Flares Twitter 0 Facebook 0 Google+ 0 0 Flares ×
  • A final static variable must be definitely initialized either
    • during declaration also known as compile time constant or
    • in a static initialize (static block) of the class in which it is declared otherwise, it results in a compile-time error.
  • You cannot initialize final static variables inside a constructor.
class Car
{
	final static double MIN_SPEED = 0; //Compile time constant
	final static double MAX_SPEED; //Blank final static Field
		
	//static initialization block
	static
	{
		MAX_SPEED = 200; //mph
	}
	
	Car()
	{
		//MIN_SPEED = 0; //ERROR
		//MAX_SPEED = 200; //ERROR
	}
}

Constants

  • Fields that are marked as final, static, and public are effectively known as constants
  • For example, the following variable declaration defines a constant named PI, whose value is an approximation of pi
  • public static final double PI = 3.141592653589793;
  • Constants defined in this way cannot be reassigned, and it is a compile-time error if your program tries to do so.

Naming a Constant

  • By convention, to name a constant we use all uppercase letters. If the name is composed of more than one word, the words are separated by an underscore (_).

Example,

ARRAY_SIZE
MAX_GRADE
PI

If a primitive type or a String is defined as a constant and the value is known at compile time, the compiler replaces the constant name everywhere in the code with its value. This is called a compile-time constant. If the value of the constant changes (for example, MAX_SPEED of a Car should be 100), you will need to recompile any classes that use this constant to get the current value.

Advantage:

  • The compiled Java class results in faster performance if variables are declared as static final.