Search code examples
javafinal

Java: Where to place declaration of final variable


I've been learning about final variables in Java from SoloLearn, and have stumbled across the following code:

    class MyClass
    {
       public static final double PI = 3.14; //defines a constant double PI = 3.14
       public static void main(String[ ] args)
       {
       System.out.println(PI); //prints 3.14
       }
    }

Why is the final variable PI declared before the main method?

When final PI is declared in the main method, the code gives an error: illegal start of expression, and it expects a semicolon between the words static and final. Why can't the final variable PI be in the main method?


Solution

  • Why is the final variable PI declared before the main method?

    Because the author of the code wanted PI to be a static member of the class, not a local variable.

    When final PI is declared in the main method, the code gives an error: illegal start of expression, and it expects a semicolon between the words static and final.

    You can't have static on the declaration of a local variable. You could have just final double PI = 3.14; in main, but it would be local to main only.