java变量要进行初始化,在Java中,为什么某些变量首先需要初始化,而其他变量仅需要声明?...

I'm trying to understand on a deeper level if I'm missing something as to understanding when Java needs an initialization of a variable vs a simply declaration. In the following code, the variable 'row' doesn't need to be assigned a value to compile and run, however, the variable 'column' does.

Note: This program does nothing of use - it's been trimmed to display only whats necessary for this question as to not waste peoples valuable time.

Here's the code snippet:

int row; //row doesn't need initialization

int column=0; //column does need initialization

for (row=0; row<2; row++){

for (column=0; column<2; column++){

}

}

System.out.print("Col:" + column + " row:" + row);

Why does row compile w/o initialization at the top, but Java thinks column "might not have been initialized."?

解决方案

The expression row = 0 (from outer loop) is guaranteed to be evaluated, therefore row variable will always be initialized before being used. The column variable would be initialized if, and only if, outer loop would iterate at least once. In other words the expresion column = 0 (from inner loop) is not guaranteed to be evaluated.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值