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

Java 定义时声明局部变量和定义后声明局部变量有什么区别?,java,local-variables,java-compiler-api,Java,Local Variables,Java Compiler Api,两者的区别是什么 public static void main(String [] ar){ int var= 10; System.out.println(var); } 及 此外,它在编译器/JVM中反映了什么?除了所使用的行数之外,没有真正的区别。这是一个风格问题,对于这种简单的情况,我将使用第一个示例 如果代码优化为本机代码,变量var可能会完全消失。int-var//为名为var的int数据类型保留内存位置 var=10//将整数10分配到上述位置 您可以单独执行这

两者的区别是什么

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


此外,它在编译器/JVM中反映了什么?

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


如果代码优化为本机代码,变量
var
可能会完全消失。

int-var//为名为var的int数据类型保留内存位置

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

您可以单独执行这些操作,也可以按照演示的步骤一步执行。编译器没有什么不同


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

在讨论代码的行为时,我们同意您的观点(工作时没有区别)。但我对在编译器和/或JVM中复制代码感兴趣。。变量何时赋值?在编译时或运行时?@Suraj赋值在运行时执行。编译器唯一要做的就是内联编译时已知的常量。谢谢你,彼得。我错误地认为,在第一种情况下,变量将在编译时被赋值,在第二种情况下,在运行时被赋值…@Suraj编译除了a)验证源代码,b)生成字节代码外,几乎没有做什么。代码本身是完美的。这两种情况都没有任何错误。我特别感兴趣的是编译器和JVM在同一领域的工作之间的差异(我认为是存在的)。
    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.
    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.