KVK
KVK

Reputation: 1289

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

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

Upvotes: 14

Views: 3388

Answers (4)

Mohit
Mohit

Reputation: 17

A instance variable if not marked final gets default value whereas a local variable do not get default value.

For instance variable "int b" to be final it has to be assigned at time of declaration or in constructor.

For local variable "int a" inside main method if it's not initialized do not get error.

Upvotes: -1

Rakesh Raka
Rakesh Raka

Reputation: 26

Local variable has no default value right , bt we can declare like this

final int a; there has no error but we cannot access it . when we try to access it , then error is occur . But this case is not for class variable .

So in your case when you access to print the value of a variable , error occur . Thanks

Upvotes: 1

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

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.

Upvotes: 12

Codebender
Codebender

Reputation: 14471

The answer is provided in JLS.

A variable can be declared final. A final variable may only be assigned to once. It is a compile-time error if a final variable is assigned to unless it is definitely unassigned immediately prior to the assignment.

What is definitive assignment

Now, in case of a local variable, it's scope is valid inside the block it's declared. And flow will be linear (from top to bottom). So the compiler can identify easily where the variable will be initialized at first.

But in case of a field, it's impossible to find which method will assign the variable first unless it's assignment in a Constructor.

So, you have to assign final fields during declaration or in a Constructor.

Upvotes: 2

Related Questions