在定义时和定义后声明局部变量有什么区别?

时间:2016-04-16 17:32:32

标签: java local-variables java-compiler-api

之间有什么区别
public static void main(String [] ar){
    int var= 10;
    System.out.println(var);
}

public static void main(String [] ar){
    int var;
    var= 10;
    System.out.println(var);
}

此外,它在Compiler / JVM中的反映是什么?

3 个答案:

答案 0 :(得分:1)

除了您使用的行数之外,没有什么真正的区别。这是一个风格问题,对于这种简单的情况,我会使用第一个例子。

如果代码已针对本机代码进行了优化,则变量var可能会完全消失。

答案 1 :(得分:0)

int var; //保留名为var

的int数据类型的内存位置

var = 10 //将整数10分配给上述位置

您可以单独执行这些操作,也可以在演示过程中一步完成。编译器没有区别。

第一个示例中的语法同时执行两个步骤,而第二个示例将步骤分开。

答案 2 :(得分:-1)

    There is no at all difference between in both of the snippets mentioned other than number of lines taken to do declaration & initialization.
    The compiler will treat both of the things in the same fashion.
    Since initialization is been done before using the local variable in both the cases, there are no chances of error like 'Variable Not Initialized' or so.