What is a Question Mark "?" and Colon ":" Operator Used for? [duplicate]
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