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

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

This is the ternary conditional operator, which can be used anywhere, not just the print statement. Its sometimes just called the ternary operator, but its not the only ternary operator, just the most common one.

Heres 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 its false you get the second one.

Try these if that still doesnt 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>);
}

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

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

Leave a Reply

Your email address will not be published.