Matan Touti
Matan Touti

Reputation: 191

Why is my use of the ?: conditional operator incorrect?

I get a compilation error while trying to compile, "not a statement", and the code is:

(checkDatabaseExist())?connectToDB() : buildDB();

when the functions are:

private boolean checkDatabaseExist() {...}
private void connectToDB(){...}
private void buildDB(){...}

any ideas?

Upvotes: 2

Views: 136

Answers (4)

Rahul
Rahul

Reputation: 16355

The ternary operator can not be used with methods/operations returning void.

The methods/expressions must return a value compatible with the reference type.

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213391

As stated in JLS - Section 15.25 - Conditional Operator: -

It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.

So, you must use an if-else construct to invoke your methods on different condition.

if (checkDatabaseExist()) {
    connectToDB();
} else {
    buildDB();
}

Upvotes: 1

Timr
Timr

Reputation: 1032

Adding to what @Jon Skeet said, a Ternary operator (What you're using) is designed to be used in this sort of way:

String s = someBoolean ? "someBoolean is true" : "someBoolean is false";

(condition) ? (value if true) : (value if false)

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1503509

Yes, you can't use the conditional operator like that. It's intended to compute one expression or another as a result. It's not intended to be a way of choosing one statement to execute or another.

Just use:

if (checkDatabaseExist()) {
    connectToDB();
} else {
    buildDB();
}

Upvotes: 5

Related Questions