-1

I'm not completely sure how to use the operators : and ?

Example: I have this code in the end of a method

return row <= -1 || row == rows || col <= -1 || col == cols ? 
            false : lifeBoard[row][col];

How would I split it up in to if/else types?

Michael
  • 644
  • 5
  • 14
  • 33

6 Answers6

6

?: (the ternary operator) works as a a compact if-else:

if (row <= -1 || row == rows || col <= -1 || col == cols) {
        return false;
}
else {
    return lifeBoard[row][col];
}

Whatever comes before the ? is the condition, between ? and : comes the result if the condition is true, and after : comes the result if the condition is false.

outlyer
  • 3,933
  • 2
  • 14
  • 18
3

This:

return row <= -1 || row == rows || col <= -1 || col == cols ? 
            false : lifeBoard[row][col];

Is equivalent to this:

if (row <= -1 || row == rows || col <= -1 || col == cols) {
    return false;
} else {
    return lifeBoard[row][col];
}

The syntax of the Ternary operator ?: is this:

Statement to evaluate ? Value if true : Value if false

It is like if/else but it can be used inside of a return statement or similar:

return (x != null ? x : "null");
Pokechu22
  • 4,984
  • 9
  • 37
  • 62
2

If/else version:

if (row <= -1 || row == rows || col <= -1 || col == cols) {
    return false;
} else {
    return lifeBoard[row][col];
}
Egor Neliuba
  • 14,784
  • 7
  • 59
  • 77
2

This is the syntax:

<boolean expression> ? <value if true> : <value if false>

Example

boolean myBool = getMyBool();
String myStr = myBol ? "myBol is true" : "myBol is false";
System.out.println(myStr);
Predrag Maric
  • 23,938
  • 5
  • 52
  • 68
2

This is a ternary operation. So for example

minVal = (a < b) ? a : b;

Would be the same as

if(a < b) {
    minVal = a;
}
else {
    minVal = b;
}
Jeremy W
  • 1,889
  • 6
  • 29
  • 37
1

It is a Conditional operator also known as Ternary operator. It is simply the compact form of if else statement wherein you don't have to use if and else separately.

Here's how it works...

"?"- anything written before the"?" is the condition

":"- anything written before the ":" is chosen as the result if the condition mentioned before "?" is true

anything written after the ":" is chosen as the result if the condition mentioned before "?" is false

This is how it works...

So splitting the given code into if/else can be easily done as follows -

    if (row <= -1 || row == rows || col <= -1 || col == cols) {
        return false;
    }
    else {
        return lifeBoard[row][col];
    }
Shubham Soin
  • 138
  • 1
  • 9