简体   繁体   English

将任意大括号作为陈述 - 它们是什么意思?

[英]Placing arbitrary braces as statements - what do they mean?

The following is a valid Java program: 以下是有效的Java程序:

public class _ {

    public static void main(String[] args) {
        {
            {
                {
                    {

                    }
                }
            }
        }
    }

}

Do those curly braces add extra semantics? 这些花括号是否会增加额外的语义? Or are they treated just like whitespace? 或者他们被视为空白?

The curly braces just create a local block scope inside your main method. 花括号只是在main方法中创建一个局部块范围。 The variables declared inside a block will not be visible outside. 在块内声明的变量在外部不可见。

This way of coding is used to minimize the scope of local variables. 这种编码方式用于最小化局部变量的范围。

public void someMethod() {
    {
        int x = 10;
        System.out.println(x); // Ok
    }
    System.out.println(x); // Error, x not visible here
}

It is a good practice to minimize the scope of the local variables you create, specially when you know they won't be used anywhere else in your program. 最小化您创建的局部变量的范围是一种很好的做法,特别是当您知道它们不会在程序中的任何其他位置使用时。 So, it doesn't make sense to let it in the larger scope till it ends. 因此,将它放在更大的范围内直到它结束是没有意义的。 Just create a local block scope, so that it will be eligible for Garbage Collection as soon as the block ends. 只需创建一个本地块作用域,这样一旦块结束,它就有资格进行Garbage Collection

Also see @Bohemian's answer below that also quotes one more benefit. 另见@Bohemian's下面@Bohemian's答案,也引用了另一个好处。

They are a code block. 它们是代码块。 They can be handy when copy-pasting code that contains local variable declarations: 当复制粘贴包含局部变量声明的代码时,它们可以很方便:

{
    int x = foo * bar;
    someMethod(x);
}
{
    int x = foo * y; // won't get "already defined variable" compile error
    someMethod(x);
}

I've also seen them used for code generation, so you can safely add some code to a method and define a variable without having to worry if it's been defined earlier in the method. 我也看到它们用于代码生成,因此您可以安全地向方法添加一些代码并定义变量,而不必担心它是否已在方法中先前定义过。

The curly braces are meant to define and limit scope. 花括号用于定义和限制范围。 Since they do not enclose any statements or declarations, they would eliminated by the compiler. 由于它们不包含任何语句或声明,因此它们将被编译器消除。

The only purpose of the extra braces is to provide scope-limit. 额外括号的唯一目的是提供范围限制。 The variable a 变量a

void ad()
    {
    int a;
    }

will only exist within those braces, and will have no scope outside of them. 只存在于那些大括号内,并且不会在它们之外。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM