I dont know what the question mark (?
) stand for in java, I was doing a small program, a Nim-game. were looking in a book, for help and saw this statement:
int pinsToTake = (min >= 2) ? 2 : 1;
I don't understand it, what will ?
represent, can it be something to do with if-statement but you put it in a variable? and the :
can be something "else"? (this things that I just said can be very misleading)
someval = (min >= 2) ? 2 : 1;
This is called ternary operator, which can be used as if-else
. this is equivalent to
if((min >= 2) {
someval =2;
} else {
someval =1
}
Follow this tutorial for more info and usage.
Its ternary operator
also referred to as the conditional operator, have a look reference
like Object bar = foo.isSelected() ? getSelected(foo) : getSelected(baz);
eg. operand1 ? operand2 : operand3
- if operand1 is true, operand2 is returned, else operand3 is returned
- operand1 must be a boolean type
- operand1 can be an expression that evaluates to a boolean type
- operand1 and operand2 must be promotable numeric types or castable object references, or null
- if one of operand2 or operand3 is a byte and the other a short, the type of the returned value will be a short
- if one of operand2 or operand3 is a byte, short or char and the other is a constant int value which will fit within the other operands range, the type of the returned value will be the type of the other operand
- otherwise, normal binary numeric promotion applies
- if one of operand2 or operand3 is a null, the type of the return will be the type of the other operand
- if both operand2 and operand3 are different types, one of them must be compatible (castable) to the other type reference
it means:
if(min >= 2)
someval =2;
else
someval =1
Its called a ternary operator See this java example too
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With