Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

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

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?

I'm sorry if this question is of low quality, but I really need clarification for this. I hope experts in Java will help me.

Well, I've already seen Semicolons in a class definition and other related questions.

Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...