Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are semicolons required in Java?

Tags:

java

syntax

A basic part of Java syntax (as well as that of most C-based languages) is that semicolons are required at the end of every statement.

However, I managed to write the following program, without using any semicolons:

class Hello extends Exception
{
    Hello(String s)
    {
        super(s)
    }
}

public class HelloWorld
{
    public static void main(String[] args) throws Hello
    {
        world((char)130)
    }

    static void world(char c) throws Hello
    {
        throw new Hello(new String(new char[]{c}))
    }
}

Running NetBeans 7.4, it warned me about the lack of semicolons, but it did work properly. However, when I posted this on CodeGolf.SE, others commented that it didn't work with javac or the Eclipse IDE. So, are semicolons required, or not?

like image 597
Ypnypn Avatar asked Mar 09 '14 19:03

Ypnypn


1 Answers

Mostly yes, semicolons are required.

When exactly they are required can be found in the Java Language Specification. For example (from chapter 14):

14.4. Local Variable Declaration Statements

LocalVariableDeclarationStatement:
    LocalVariableDeclaration ;

14.6. The Empty Statement

EmptyStatement:
    ;

14.8. Expression Statements

ExpressionStatement:
    StatementExpression ;

14.10. The assert Statement

AssertStatement:
    assert Expression1 ;
    assert Expression1 : Expression2 ;

14.13. The do Statement

DoStatement:
    do Statement while ( Expression ) ;

And so on and so on. As you can see the semicolons are actually right there in the spec, as literal text. I find these language specs always a bit funky to read but basically they are defining the syntax from small, sort-of atomic concepts such as 'EmptyStatement', keywords and literal text, up to the higher level structures such as do-while, if-then-else etc. So if you want to know exactly when you need a semicolon or not, study the spec carefully.

like image 88
Stijn de Witt Avatar answered Sep 28 '22 22:09

Stijn de Witt