Detailed explanation of the use of Java compound statements

Like C language and other languages, the compound statement of Java language is a statement with the whole block as the unit, so it is also called block statement. Let's take a look at the usage methods and examples of compound statements.

A compound statement begins with an open bracket '{' and ends with a closed bracket '}'. I believe you have come into contact with this compound statement in the process of learning Java. For example, when defining a class or method, the class body is marked with "{}" as the start and end mark, and the method body is also marked with "{}". Each statement in a compound statement is executed from top to bottom. The compound statement takes the whole block as the unit, which can be used where any single statement can be used, and the compound statement can also be nested in the compound statement.

Instance: create a class compound in the project and define a compound statement block in the main method, which contains another compound statement block. The code is as follows:

The operation results are as follows:

40 false hello java

Note: when using a compound statement, it should be noted that the compound statement creates a scope for local variables, which is a part of the program. In this scope, a variable is created and can be used. If the variable is used outside the scope of a variable, an error will occur. For example, in this example, if the variables y, Z and B are used outside the compound statement, an error will occur, and the variable x can be used in the whole method body.

I hope this article is helpful to you.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>