java 大括号,Java中的'{'符号(大括号)表示什么?

I'm currently learning Java, and was given a question that seems to defy a simple answer:

What is the meaning of the following symbol in Java: {?

Of course, there are the common meanings: the body of an if statement, for loop, other control structures. But then it could also be the start of a method, or an initializer - these seem to have less in common.

I've spent a good bit of time searching for a single definition for this symbol in the context of Java, but haven't found anything that would suffice here.

What is an all-encompassing definition of what the opening curly brace indicates in Java?

解决方案

The question from your instructor seems not so great because there isn't a single unified meaning of the { symbol in Java.

In the context of a statement, the { symbol is used to denote the start of a block statement. This accounts for all the uses of { with if statements, while loops, for loops, do ... while loops, switch statements, etc., which technically only apply to a single statement but are often used with block statements:

if (x == 0) {

statementOne();

statementTwo();

}

In the context of a method or type (class/interface/enum/annotation), the { symbol is used to denote the beginning of the body of a class or a method:

public class NewClass {

...

public void foo() {

...

}

}

It can also be used inside a class to declare an initializer or static initializer block:

class MyClass() {

static int x;

static {

x = somethingHorrible();

}

};

In the context of an array literal, the { symbol is used to denote the beginning of the list of elements used inside that literal:

int[] arr = new int[] {1, 3, 7};

Each of these uses of the open brace symbol is different from all the others. In fact, the language would work just fine if we used a different symbol for each of these different contexts.

I think that the best answer to your question is that { is used in contexts where some group of things will be treated as a unit, whether it's a block statement (many statements treated as a single one), a class (many methods and fields treated as a single object), a method (many statements treated as a single unified piece of code), an initializer (many things that need to be done at once), etc.

In the majority of these contexts, as the comments have pointed out, the brace introduces a new scope. Statement blocks, class bodies, initializer bodies, and function bodies all introduce a new scope, and that is definitely something important to keep in mind. (Array initialization doesn't do this, though.)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值