Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "?" mean in Java? [duplicate]

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)

like image 967
Alexein Avatar asked Aug 17 '12 12:08

Alexein


3 Answers

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.

like image 148
Nandkumar Tekale Avatar answered Oct 16 '22 02:10

Nandkumar Tekale


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
like image 35
Harmeet Singh Avatar answered Oct 16 '22 04:10

Harmeet Singh


it means:

if(min >= 2) 
   someval =2;
else 
   someval =1

Its called a ternary operator See this java example too

like image 37
CloudyMarble Avatar answered Oct 16 '22 03:10

CloudyMarble