News Ticker

Final Variables

Final variables are not assigned a default value when an object is instantiated.

If a value is not assigned at the same time that the variable is declared a value can be assigned in either a constructor or an initialisation block but not both. See example below:

This example shows that the final variable is assigned a value in a initialisation block.

[sourcecode language=”java” toolbar=”false”]
public class F {

{
c=2;
}
final int c; // Declared textually after the assignment.

public static void main(String[] args)
{
F f=new F();
System.out.println(f.c);
}
}
[/sourcecode]

Word of warning: if the code in the constructor or initialisation block uses the final variable then the variable must be declared in the code before it is used. The error is an “illegal forward reference” and is detailed more here: 8.3.2.3 Restrictions on the use of Fields during Initialization

1 Trackback / Pingback

  1. Welcome « alex.theedom

Leave a Reply

%d bloggers like this: