Is a line in a Java program the same thing as a statement?
I'm a Java noob. I've only used it for a few days and I'm still trying to figure it all out. In a program, is a 开发者_JS百科line the same thing as a statement?
No. I can write:
int x = 1; int y = 2;
That's one line, and two statements.
No. The Java compiler doesn't look at lines, spacing, or other formatting issues when compiling a program. It just wants to see the ;
at the end of each statement. This line would work just fine:
int i = 13; i += 23;
However, doing things like this can--and most likely will--cause readability issues with the source code. For this reason, it isn't recommended.
It is also possible for a single statement to span multiple lines:
int i =
13;
In a program, is a line the same thing as a statement?
No.
Want to know the difference? Start with the JLS §14.5: Blocks and Statements:
Statement: StatementWithoutTrailingSubstatement LabeledStatement IfThenStatement IfThenElseStatement WhileStatement ForStatement StatementWithoutTrailingSubstatement: Block EmptyStatement ExpressionStatement AssertStatement SwitchStatement DoStatement BreakStatement ContinueStatement ReturnStatement SynchronizedStatement ThrowStatement TryStatement StatementNoShortIf: StatementWithoutTrailingSubstatement LabeledStatementNoShortIf IfThenElseStatementNoShortIf WhileStatementNoShortIf ForStatementNoShortIf
According to Java grammar:
Statement:
Block
if ParExpression Statement [else Statement]
for ( ForInitOpt ; [Expression] ; ForUpdateOpt ) Statement
while ParExpression Statement
do Statement while ParExpression ;
try Block ( Catches | [Catches] finally Block )
switch ParExpression { SwitchBlockStatementGroups }
synchronized ParExpression Block
return [Expression] ;
throw Expression ;
break [Identifier]
continue [Identifier]
;
ExpressionStatement
Identifier : Statement
Based on this you can easily see that one statement can span multiple lines but also single line can host multiple statements. Also note that statement is a very broad term.
This line includes two statements:
j = 5; j += 3;
So, a line is not necessarily a statement...
Only by common practice, and for readability. In Java statements are terminated with semicolons, or in the case of blocks, by pairs of curlybraces ( { } ).
精彩评论