java main final,为什么Final变量不需要在java中的main方法初始化?

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

}

}

解决方案

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值