在Java中,为什么某些变量首先需要初始化,而其他变量仅需要声明? [英] In Java, why do certain variables need initialization at first and others only need declaration?

查看:114
本文介绍了在Java中,为什么某些变量首先需要初始化,而其他变量仅需要声明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想了解何时需要Java初始化变量而不是简单声明的内容,我想更深入地了解。在以下代码中,不需要为变量 row分配值来进行编译和运行,但是,变量 column却需要赋值。

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.

下面是代码段:

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

为什么不进行初始化编译在顶部,但是Java认为可能尚未初始化。?

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

推荐答案

表达式 row = 0 (来自外部循环)保证可以被求值,因此 row 变量将始终在使用之前初始化。 column 变量将在且仅在外部循环至少迭代一次的情况下初始化。换句话说,表示要评估的表达式 column = 0 (来自内部循环)。

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.

这篇关于在Java中,为什么某些变量首先需要初始化,而其他变量仅需要声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆