-1

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.

RAVE CLO
  • 14
  • 3

2 Answers2

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