-6

I have this little formula:

this.size = size >= MIN_SIZE ? size : MIN_SIZE;

The values are not my problem, but the point is I don't understand what does the symbol >= is doing over there, and also the ? and the :

Can anybody explain me what those symbols are doing over there? This is not an IF statement, it's just the beginning of a method.

Wooble
  • 87,717
  • 12
  • 108
  • 131
Brian James
  • 25
  • 1
  • 5
  • 1
    It's called a ternary operator. – Gergo Erdosi Jul 02 '14 at 16:43
  • 2
    possible duplicate of [What is the Java ?: operator called and what does it do?](http://stackoverflow.com/questions/798545/what-is-the-java-operator-called-and-what-does-it-do) – Wooble Jul 02 '14 at 16:44

1 Answers1

2
this.size = size >= MIN_SIZE ? size : MIN_SIZE;

is the shortcut for

 if (size >= MIN_SIZE){
      this.size = size; //i.e. keep it.
 }else{
     this.size = MIN_SIZE;
 }

Or in generic speech:

value = (condition)? optionA : optionB;

equals

if (condition){
   value = optionA;
}else{
   value = optionB;
}
dognose
  • 20,360
  • 9
  • 61
  • 107
  • Not quite, though close. The ternary condition (`? ... :`) is an expression, whereas if you expand it out to that if-else, it looks like it becomes two statements. For instance, you can't do `someCondition ? foo() : bar()` as a standalone. I only mention it because it's caused confusion before (I can't remember the questions offhand that I've seen relating to it). – yshavit Jul 02 '14 at 16:53
  • ok guys thank you for your time and for your expanations! – Brian James Jul 02 '14 at 17:32
  • @yshavit hmm... works for me? http://jdoodle.com/a/7M – dognose Jul 02 '14 at 18:16
  • @dognose I meant without the `s =`. If the ternary were really just a shortcut for an if-else, then this would be valid: `public static void main(String[] args) { "".equals("")? foo() : bar(); }`. That's not allowed. – yshavit Jul 02 '14 at 18:48
  • @yshavit ofcourse it is just about value assignment. Otherwhise i would have written `if (size >= MIN_SIZE){ size; }else{ MIN_SIZE; }` - which is not valid ofc. (note the missing `this.size=`) – dognose Jul 02 '14 at 19:04
  • Point is, it's not really a shortcut for what you wrote. If anything, the "expanded" form would look something [this](https://gist.github.com/yshavit/8ba3124a520b7e07cb2a). Again, I only mention it because people _have_ gotten confused on that distinction in the past -- especially in Java 7 and below, where type inference can make the ternary operator fail to compile things that do compile in the expanded form. – yshavit Jul 02 '14 at 19:10