6

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 line the same thing as a statement?

Benny
  • 71
  • 2

6 Answers6

5

No. I can write:

int x = 1; int y = 2;

That's one line, and two statements.

Eric
  • 95,302
  • 53
  • 242
  • 374
4

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
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
4

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;
Samuel Edwin Ward
  • 6,526
  • 3
  • 34
  • 62
fireshadow52
  • 6,298
  • 2
  • 30
  • 46
4

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
2

This line includes two statements:

j = 5; j += 3;

So, a line is not necessarily a statement...

Costis Aivalis
  • 13,680
  • 3
  • 46
  • 47
2

Only by common practice, and for readability. In Java statements are terminated with semicolons, or in the case of blocks, by pairs of curlybraces ( { } ).

Mike Sokolov
  • 6,914
  • 2
  • 23
  • 31