What is a Question Mark "?" and Colon ":" Operator Used for?

Deepend picture Deepend · Apr 26, 2012 · Viewed 314.1k times · Source

Two questions about using a question mark "?" and colon ":" operator within the parentheses of a print function: What do they do? Also, does anyone know the standard term for them or where I can find more information on their use? I've read that they are similar to an 'if' 'else' statement.

int row = 10;
int column;
while (row >= 1)
{
    column = 1;
    while(column <= 10)
    {
        System.out.print(row % 2 == 1 ? "<" : "\r>");
        ++column;
    }
    --row;
    System.out.println();
}

Answer

Brendan Long picture Brendan Long · Apr 26, 2012

This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.

Here's a good example from Wikipedia demonstrating how it works:

A traditional if-else construct in C, Java and JavaScript is written:

if (a > b) {
    result = x;
} else {
    result = y;
}

This can be rewritten as the following statement:

result = a > b ? x : y;

Basically it takes the form:

boolean statement ? true result : false result;

So if the boolean statement is true, you get the first part, and if it's false you get the second one.

Try these if that still doesn't make sense:

System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");