Vedant Terkar Vedant Terkar - 4 years ago 238
Java Question

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

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

What I wonder is, In C++ after class definition a semicolon(

;
) is Required. But in java it isn't required.

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 Isn't Required


That's Fine I've understood it.

But 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 is it so? what does semicolon in class definition for
java
stands for?

Sorry If question is of low quality, But I really need clarification for this. Hope experts in java will help me.

Well I've already seen:

semicolons in a class definition. and other relatives.

Thanks in advance.

Answer Source

I've compiled and executed both the program snippets shown for java and they both work. can anyone explain why is it so?

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

what does semicolon in class definition for java stands 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();)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download