Home  |   STIU  |   WOW  |   SCJP  |   SCDJWS   |   JEE FAQ  |   About US  |  

FAQ
  Java FAQ
  JSP FAQ
  Servlet FAQ
 

Advertisement

XyzWs Java FAQ:
Where can final variables be initialized?


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend


Previous Next vertical dots separating previous/next from contents/index/pdf Contents
Advertisement
XyzWs Java FAQ : Where can final variables be initialized?

Where can final variables be initialized?


There are three forms of final variables: class final variables, instance final variables, and local final variables. There is no requirement to initialize a final variable at declaration but it must initialize before using it.

You can only initialize a final variable once.

  • For class final variables, the variables can be initialized in either the declaration or static initializer:
    class Program {
        static final int i1 = 10;
        static final int i2;
        static {
            i2 = 10;
        }
    }
    
  • For instance final variables, the variables can be initialized in the declaration, instance initializer, or constructor:
    class Program {
        final int i1 = 10;
        final int i2;
        final int i3;
        {
            i2 = 10;
        }
        
        Program() {
            i3 = 10;
        }
    }
    
  • For local final variables, the variables can be initlialized in the declaration or any place after its declaration. The local final variables must be initializd before they are used.
    class Program {
        void method() {
             final int i1 = 10;
             final int i2;
             System.out.println(i1);
             i2 = 10;
             System.out.println(i2);
             return ;
        }
    }
    

 


Previous Next vertical dots separating previous/next from contents/index/pdf Contents

Support  | Feedback  | Help