Can someone please explain this java syntax for me.
public boolean isDead() { return numFightersAlive() == 0 ? true : false; }
I am new to java and I was wondering what kind of syntax that is. Normally I would create a variable and return the boolean variable but it's my first time seeing a question mark in a code.
Asked
Active
Viewed 50 times
-1

RAVE CLO
- 14
- 3
-
1It is called a ternary operator. – Eyeslandic Nov 16 '20 at 06:54
-
3Note that this is an example of a _really bad use_ of the ternary, since you can just as easily say `return numFightersAlive() == 0`. – chrylis -cautiouslyoptimistic- Nov 16 '20 at 06:56
2 Answers
2
After the question mark is the "then" part, after colon is the "else" part.
So this is shorthand syntax for
if (numFightersAlive() == 0) {
return true;
} else {
return false;
}
It can actually be simplified to be just
return numFightersAlive() == 0
This would give an equivalent result

Maria
- 35
- 3
-
To add in, a while ago I asked something very similar and OP might want to take a look: https://stackoverflow.com/questions/64096020/how-does-the-ternary-operator-work-in-this-piece-of-code – Mint Nov 16 '20 at 06:58
0
This is called ternary. It's a shortened version of an if, but it's not better than an if all the time.
The syntax of a ternary is as follows:
(condition) ? result in case of being true: result in case of being false
In this case: The return is asking a condition. Is the condition equal to zero?
If it is true, return will have a true value, if it is false return will have a false value.
public boolean isDead() { return numFightersAlive() == 0 ? true : false; }

Avalon
- 34
- 3