Why is the semicolon not required but allowed at the end of a class definition?

前端 未结 5 1436
忘了有多久
忘了有多久 2020-12-18 18:57

I\'m trying to shift from C++ to Java.

What I wonder is, in C++, after a class definition, a semicolon (;) is required, but in Java it isn\'t.

T

5条回答
  •  旧巷少年郎
    2020-12-18 20:00

    I've compiled and executed both the program snippets shown for Java, and they both work. Can anyone explain why this is so?

    It is allowed because the Java Grammar says it is allowed; See JLS 7.6.

    What does the semicolon at the end of a class definition in Java stand for?

    Nothing. It is optional "syntactic noise".

    The JLS explains it as follows:

    Extra ";" tokens appearing at the level of type declarations in a compilation unit have no effect on the meaning of the compilation unit. Stray semicolons are permitted in the Java programming language solely as a concession to C++ programmers who are used to placing ";" after a class declaration. They should not be used in new Java code.


    (Note that this is NOT an "empty statement". An empty statement (JLS 14.6) appears in a syntactic context where a statement is allowed. The presence of an empty statement can change the meaning of your code; e.g. if (a == b) ; c(); versus if (a == b) c();)

提交回复
热议问题