Shiladittya Chakraborty
Shiladittya Chakraborty

Reputation: 4418

Why ; showing exception

As I know ; is an empty statement. It's specified in section 14.6 of the JLS:

An empty statement does nothing.

EmptyStatement: ;

Execution of an empty statement always completes normally.

When I used double defaultValue = 0.0;; then its working fine but I faced an issue when I used below code then its throw error :

public double getX() {
    return x;;  // Throws unreachable code
}

Why its throwing an error?

Upvotes: 2

Views: 93

Answers (3)

ChiefTwoPencils
ChiefTwoPencils

Reputation: 13950

Because it follows a return; it's always unreachable code as the error suggests.

Any statement that follows an unconditional return is, by definition, unreachable. So, sure it's valid; in fact, it could be any valid statement (go ahead and try) and it will behave the same.

It's unreachable because return returns immediately and therefore no additional code can be executed after it.

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522817

Java is throwing an error because the empty statement ; comes after your return statement and therefore will never be reached:

public double getX() {
    return x;   // your program will always return from getX() here
    ;           // this line will never be reached
}

Note that this is caught by the compiler, and there is nothing inherently wrong with the empty statement being there.

The Java compiler enforces this rule to minimize the size of run time bytecode by removing code which will never execute.

Upvotes: 3

Tagir Valeev
Tagir Valeev

Reputation: 100349

It's a valid statement, but it's also an unreachable statement as specified in JLS 14.21:

It is a compile-time error if a statement cannot be executed because it is unreachable.

The following text describes how to determine the unreachable statements. In particular:

An empty statement can complete normally iff it is reachable.

A break, continue, return, or throw statement cannot complete normally.

So as return statement cannot complete normally, the following statements within the same block become unreachable.

Upvotes: 7

Related Questions