java - for循环造对象,造了很多重复的s对象,为什么不报错?
大家讲道理
大家讲道理 2017-04-18 09:51:15
0
7
550

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(7)
迷茫
// 循环执行 10 次,会产生 10个 {} 代码块,互不冲突
for (int i = 0;i < 10;i ++) { // ↓
    int s = i; // 中间这一部分是 s 的作用域,出了作用域 s 是不存在的
} // ↑
刘奇
  1. First of all, s is of type int, which is a basic type, not an Object type, so there is no such thing as "creating many duplicate s objects"

  2. What is created here is a variable of type int. This variable is stored on the stack

  3. Even if you set the number of loops to Integer.MAX_VALUE, no error will be reported. The specific reason is not known, but the compiler will optimize the code so that the same memory area is actually used every time instead of opening it every time. A new memory area

小葫芦

You can try Integer haha

阿神

1. The first thing you need to understand is that there is no object named s here. The s and i in the code are just references to objects, which are equivalent to pointers in C language. They just point to this object space. logo.
2. Each of your for loops declares a reference with the same name. Then the compiler can distinguish these references with the same name, so no matter how many times you loop, you actually only have one named 's ' reference. And it is initialized in the first for loop, and each subsequent loop assigns a value to this reference with the same name.
3. If you want to see the print result, put system.out in the valid domain of the local variable.

Peter_Zhu

1. This code does not create an object. Int is a basic data type, not an object.
2. This code will be optimized by the compiler. I guess the result may be in the form of int s = 9;. You can javap it to see

刘奇

Because you are using the java compiler.

刘奇

Where does int come from? It just keeps changing the value of the stack

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template