Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Final variable doesn't require initialization in main method in java?

Tags:

java

final

When I am just trying to do some program in Java.I try to use final variable,I know that final variable must be initialized at the time of declaration, but inside the main method it accepts the final variable with out initialization. I don't know what's the reason.Can any one tell me the reason.

Thank you

code:

class name
{
     final int b; //here shows error
     public static void main(String args[])
    {
        final int a; // here no error... why?
        System.out.println("hai");
    }
}
like image 727
KVK Avatar asked Jul 24 '15 05:07

KVK


People also ask

Can we declare final variable without initialization in Java?

If you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them.

Does a final variable require initialization?

If you declare a variable as final, it is mandatory to initialize it before the end of the constructor. If you don't, a compile-time error is generated.

Can we declare final variable in main method in Java?

Core Java bootcamp program with Hands on practiceYes, we can declare the main () method as final in Java. The compiler does not throw any error. If we declare any method as final by placing the final keyword then that method becomes the final method. The main use of the final method in Java is they are not overridden.

Can we declare final variable inside method?

The method variable is scoped within a method's call life-cycle. The final modifier ensures that upon initialization, it cannot be re-initialized within the scope of the method of that call. So yes, per method call, that variable is made final.


1 Answers

For instance variable level

  • A final variable can be initialized only once.

  • A final variable at class level must be initialized before the end of the constructor.

For local (method) level

  • A final variable at method level can be initialized only once.
  • It must be initialized before it is used

So basically if you don't use a local final variable you can also skip it's initialization.

If the variable is at instance level you have to initialize it in the definition or in the costructor body.

In your code you have an instance variable final int b that is never initialized so you have an error.

You have also a local variable final int a that is never used. So you haven't an error for that variable.

like image 196
Davide Lorenzo MARINO Avatar answered Oct 14 '22 18:10

Davide Lorenzo MARINO