How to assign a value to static final variables in Java?

Assigning values to static final variables in Java:

In Java, non-static final variables can be assigned in the constructor or through declarations. However, static final variables cannot be assigned in the constructor; they must be assigned a value in the declaration.

For example, the following program works fine.

class Test {

	// i could be assigned a value here
	// or constructor or init block also.
	final int i;
	Test()
	{
		i = 10;
	}

	// other stuff in the class
}

If we make i statically final, then we must use the declaration to assign a value to i.

class Test {

	// Since i is static final,
	// it must be assigned value here
	// or inside static block .
	static final int i;
	static
	{
		i = 10;
	}

	// other stuff in the class
}

This behavior is obvious because static variables are shared among all objects of the class; creating new objects will change the same static variables, and if the static variable is the final variable, this is not allowed.

 

Submit Your Programming Assignment Details