if条件/for循环在Java中是否会创建新的变量作用域?

huangapple go评论69阅读模式
英文:

Does if condition/ for loop makes a new variable scope in java?

问题

以下是您要翻译的内容:

我有一个类似这样的问题:

考虑以下Java程序

class main_class
{
    public static void main(String args[])
    {
        int x = 9;
        if (x == 9)
        {
            int x = 8;
            System.out.println(x);
        }
    }
}

A. 9
B. 8
C. 编译错误
D. 运行时错误

我选择了B,但我在本地环境中运行时发现我错了,if条件中不允许重复的变量。但是我想的是,我在编码时总是使用类似于for(int i=0;i<len;i++),但是“i”没有重复,难道不是“{}”表示一个新的变量作用域吗?这让我有点困惑。

我在我的VS Code环境中进行了本地操作,如下所示:
点击此处查看图像描述

英文:

I got a question like this:

Consider the following Java program

class main_class
{
    public static void main(String args[])
    {
        int x = 9;
        if (x == 9)
        {
            int x = 8;
            System.out.println(x);
        }
    }
}

A.9
B.8
C.Compilation Error
D.Runtime Error

I chose B, but I operated in my local environemnt and I find I'm wrong, the duplicated variable is not allowed in if condition. But what I thought is I always use for(int i=0;i<len;i++) when I'm coding, but the "i" is not duplicated, doesn't "{}" means a new variable scope? it makes me a little confused.

The local operation is conducted as below on my VS code env
enter image description here

答案1

得分: 2

是的,每个块在Java中都是一个新的作用域 - 但根据JLS 6.4的规定:

> 如果在v的作用域内使用局部变量v的名称来声明一个新变量,除非新变量在v的作用域内声明在类或接口声明中,否则将在编译时出现错误。

因此,拥有一个名为v字段,然后声明一个名为v的局部变量是可以的,但你不能声明两个名为v的嵌套局部变量声明(除了局部类声明等)。

在你的另一段代码中:

for (int i = 0; i &lt; 100; i++) {
}
for (int i = 0; i &lt; 100; i++) {
}

...每个i变量的作用域是for循环本身。根据JLS 6.3的规定:

> 在基本for语句的ForInit部分(§14.14.1)中声明的局部变量的作用域包括以下所有内容:
>
> - 它自己的初始化程序
> - 在for语句的ForInit部分中更多的声明符
> - for语句的Expression和ForUpdate部分
> - 包含的Statement

因此,这类似于编写:

{
    for (int i = 0; i &lt; 100; i++) {
    }
}
{
    for (int i = 0; i &lt; 100; i++) {
    }
}

...显然,没有嵌套的i声明。这两个变量都不是在另一个变量的作用域内声明的。

英文:

Yes, each block is a new scope in Java - but as per JLS 6.4:

> It is a compile-time error if the name of a local variable v is used to declare a new variable within the scope of v, unless the new variable is declared within a class or interface declaration appearing within the scope of v.

So it's fine to have a field called v and then declare a local variable called v, but you can't declare nest two local variable declarations of v (aside from local class declarations etc).

In your other code of:

for (int i = 0; i &lt; 100; i++) {
}
for (int i = 0; i &lt; 100; i++) {
}

... the scope of each i variable is the for loop itself. As per JLS 6.3 :

> The scope of a local variable declared in the ForInit part of a basic for statement (§14.14.1) includes all of the following:
>
> - Its own initializer
> - Any further declarators to the right in the ForInit part of the for statement
> - The Expression and ForUpdate parts of the for statement
> - The contained Statement

So it's similar to writing:

{
    for (int i = 0; i &lt; 100; i++) {
    }
}
{
    for (int i = 0; i &lt; 100; i++) {
    }
}

... clearly there's no nesting of the declarations of i. Neither variable is declared within the scope of the other.

答案2

得分: 0

你可能也会混淆以下两个示例。

class main_class
{
    public static void main(String args[])
    {
        int x = 9;
        { 
            // 在第二次声明期间,x仍然在范围内。
            int x = 10; // 编译问题,因为另一个x仍然在此范围内
        }
// 相对于
        {
            int y = 9;
        }
        int y = 10; // 没问题。第二次声明没问题,因为范围不共享。
                    // 第一个y在第二次声明之前超出范围。
    }

<details>
<summary>英文:</summary>

You also may be confusing the following two examples.

class main_class
{
public static void main(String args[])
{
int x = 9;
{
// x still in scope during second re-declaration.
int x = 10; // compilation issue other x still in this scope
}
// vs
{
int y = 9;
}
int y = 10; // OK. Second declaration fine since scope is not shared.
// first y goes out of scope prior to second declaration.
}

答案3

得分: 0

这里涉及Java中的变量作用域概念。更多详细信息请查看您的问题链接:https://softwareengineering.stackexchange.com/questions/271683/why-can-we-use-the-same-name-for-local-variable-in-different-scopes

英文:

There is this concept of variable scope in Java.
More details to your question here https://softwareengineering.stackexchange.com/questions/271683/why-can-we-use-the-same-name-for-local-variable-in-different-scopes

huangapple
  • 本文由 发表于 2023年6月6日 16:30:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76412786.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定