سؤال

I noticed that in one of my classes, I had the following:

public void foo() {
    int i = 4;
    i = 9 + 0;;
    return;
}

Two ;; in a row. Why isn't this an error? Should it be? From my understanding, it is just an "extra line" of code that the compiler reads. Does this waste performance? Also, if it really is empty, why can't I have two ;; after the return? (such as return;;)?

EDIT: What is a use for this in practice?

هل كانت مفيدة؟

المحلول

Why isn't this an error?

Because the language allows you to write a single ; on a line to denote an empty line. You can place as many ; next to each other. See JLS §14.6 - Empty Statement.

Does this waste performance?

I don't think so. You shouldn't really be worried about performance for such a minute typo. IMO, the extra semi-colon would not make it to the bytecode. So, no runtime performance difference would be there.

Also, if it really is empty, why can't I have two ;; after the return?

You can't put any statement after return statement, because that is not going to be executed anyways. That will be an unreachable statement. See JLS §14.21 - Unreachable Statements.

What is a use for this in practice?

One use which I can think of this is in an enum which you want to use as utility class. In such enum, you just want to define some static methods, and not any constant. Since defining constants in an enum is mandatory, it is not allowed to write methods preceding any constants. In that case, you would write your enum like this:

enum Utility {
    ;   // Denote the end of constant declaration. You can't omit this ';'

    // Start writing your static methods.
}

نصائح أخرى

In java, blank statements are allowed. JLS §14.6 - Empty Statement

You cannot do return;; because the blank statement will be unreachable code, which is not allowed. JLS 14.21 Unreachable Statements

In terms of wasting performance, I believe it would make your compile time a little longer. But statement;; and statement; should compile to identical bytecode, and thus not effect run-time performance.

Blank statements are also the reason that you have to be very careful with your loop syntax. Many times we've seen posts on here where people have:

while(condition);
{
    //code
}

This is an infinite loop, because there is a blank statement that follows the while, so it's loop body is empty.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top