Hot Posts

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.

    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);    
        }    
    }  

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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: