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.
That is, in C++:
class Person {
public:
string name;
int number;
}; // Note this semicolon
But in Java:
class Person {
public String name;
public int number;
} // Semicolon is not required
That's fine, I understand that.
However, my problem is:
Java also works when I add semicolon at end of class definition, like:
class Person {
public String name;
public int number;
}; // Now this semicolon is confusing me!
I've compiled and executed both the program snippets shown for Java, and they both work. Can anyone explain why this is so? What does the semicolon at the end of a class definition in Java stand for?
Well, I've already seen Semicolons in a class definition and other related questions.
Thanks in advance.
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();
)