简体   繁体   English

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

[英]What is difference between declaring local variable at the time of definition and after definition?

What is the difference between 之间有什么区别

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

and

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

moreover, what it reflects in Compiler/JVM? 此外,它在Compiler / JVM中的体现是什么?

There is no real difference, except the number of lines you used. 除了您使用的行数之外,没有任何实际区别。 It is a matter of style and for such simple case I would use the first example. 这是一个风格问题,对于这种简单的情况,我将使用第一个示例。

If the code were optimized to native code, the variable var might disappear entirely. 如果代码针对本机代码进行了优化,则变量var可能会完全消失。

int var; int var; //reserves the memory location for an int data type named var //为名为var的int数据类型保留内存位置

var = 10 //assigns the integer 10 to the above location var = 10 //将整数10分配给上述位置

You can do these separately or in one step as you demonstrated. 您可以单独执行这些操作,也可以按照说明一步执行。 There is no difference to the compiler. 编译器没有区别。

Your syntax in the first example does both steps at the same time, whereas your second example separates the steps. 第一个示例中的语法同时执行两个步骤,而第二个示例中的语法则分开。

    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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java中的声明和定义有什么区别? - What is the difference between declaration and definition in Java? 在getInstance()方法或实例变量定义中初始化单例是否存在功能差异 - Is there a functional difference between initializing singleton in a getInstance() method, or in the instance variable definition 磁贴定义中的center和body属性有什么区别? - What is the difference between center and body attribute in tiles definition? 骆驼组件定义:componentProperties和properties有什么区别? - Camel Component Definition : What is the difference between componentProperties and properties? Spring Core:应用上下文和上下文定义有什么区别? - Spring Core: What is the difference between an Application Context and a context definition? 创建 object 和声明 class 变量的新关键字有什么区别? - What is difference between new keyword for create object and declaring class variable? 在Activity中声明最终变量并在onCreate方法上实例化它之间有什么区别? - What is the difference between declaring a final variable in an Activity and instantiating it on the onCreate method? 声明一个字符串和将其声明为final之间有什么区别? - What is the difference between declaring a String and declaring it as final? 声明变量类型之间的区别 - Difference between declaring type of variable 线程CPU时间的定义是什么? - What is the Definition of Thread CPU Time?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM