Final

final is a keyword used to make a particular thing constant! Means, to make the value supplied in the initial phase fixed thereby NOT allowing any changes to the value at runtime.

It can be applied to fields or variables, methods and class as well.

fields -> the field's value can NOT be changed!

methods -> the method can NOT be overridded (by subclasses obviously)!

class -> the class can NOT be subclassed or extended!

Effects of final modifier

One sample program and thought:

class Test8
{
public static void main(String a[])
{
byte b = 1;
char c = 2;
 
c = b; // 1
}
}

Question is :

When we compile Test8.java it gives compile time error at line marked 1, 
but when we make variable b as final, then program compiles and runs fine..
 
Explain me.

The answer given by marc weber is :

An expression may be assigned to a variable of type byte, short, or char if the expression represents a compile-time constant of type byte, short, char, or int that will "fit" in the variable type. (See JLS 5.2 Assignment Conversion. -> of Java Lang Spec 3rd edition for J2SE 5.0)

In this example, if the variable 'b' is not final, then it does not represent a compile-time constant, and therefore cannot be assigned to the char variable 'c' without an explicit cast.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.