Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

Which operator uses question mark and colon?

They are called the ternary operator since they are the only one in Java.

What does question mark and colon mean in Java?

Use Question Mark and Colon Operator in Java The first is a conditional expression that returns a boolean value. The second and third are the values before and after the colon. It returns the value before the colon if the conditional expression is evaluated as true ; otherwise, it returns the value after.

What is the question mark operator called?

The so-called “conditional” or “question mark” operator lets us do that in a shorter and simpler way. The operator is represented by a question mark ? . Sometimes it's called “ternary”, because the operator has three operands. It is actually the one and only operator in JavaScript which has that many.

What is the question mark used for in PHP?

In PHP 7, the double question mark(??) operator known as Null Coalescing Operator. It returns its first operand if it exists and is not NULL; otherwise, it returns its second operand. It evaluates from left to right.


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.");

Thats an if/else statement equilavent to

if(row % 2 == 1){
  System.out.print("<");
}else{
  System.out.print("\r>");
}

a=1;
b=2;

x=3;
y=4;

answer = a > b ? x : y;

answer=4 since the condition is false it takes y value.

A question mark (?)
. The value to use if the condition is true

A colon (:)
. The value to use if the condition is false


Also just though I'd post the answer to another related question I had,

a = x ? : y;

Is equivalent to:

a = x ? x : y;

If x is false or null then the value of y is taken.


Maybe It can be perfect example for Android, For example:

void setWaitScreen(boolean set) {
    findViewById(R.id.screen_main).setVisibility(
            set ? View.GONE : View.VISIBLE);
    findViewById(R.id.screen_wait).setVisibility(
            set ? View.VISIBLE : View.GONE);
}