3

Possible Duplicate:
What is the Java ?: operator called and what does it do?

Maybe this is a duplicated question to some other questions here but I could not find it.

Yesterday I saw a guy using a new way of writing the if statement by using ? and : and I'm not sure what do they all mean.

If someone could point me out to a tutorial or an already answered question I would so much appreciated.

Community
  • 1
  • 1
Sobiaholic
  • 2,927
  • 9
  • 37
  • 54
  • 3
    There you go: http://stackoverflow.com/questions/798545/what-is-the-java-operator-called-and-what-does-it-do – Alfabravo Dec 19 '11 at 20:00
  • Don't use them too much, there isn't a lot worse then nested ternary operators. – Desmond Zhou Dec 19 '11 at 20:02
  • @DesmondZhou oh! I see lot of Prof. java programmers use this operator. In fact they even use it when they declare a variable :S – Sobiaholic Dec 19 '11 at 20:04
  • 2
    @iMohammad yes thats what you want to use it for, use it for assignment to variables concisely but not as a replacement to if statements. For example, don't put methods with side-effect in them, and don't nest them. Have fun! – Desmond Zhou Dec 19 '11 at 20:17
  • I've seen nested ternary operators before. They're unsettling. – Nick Coelius Dec 19 '11 at 20:47

5 Answers5

7

The conditional operator, it's a type of ternary operator

wikipedia - ?:

wikipedia - ternary operation

loosebazooka
  • 2,363
  • 1
  • 21
  • 32
6
(condition) ? (what happens if true) : (what happens if false);

Example use:

int a = 1;
int b = (a == 1) ? 2 : (a + 1);
5

It's a ternary operator. General form:

expr1 ? expr2 : expr3

If expr1 evaluates to true, the returned result is expr2, otherwise it's expr3. Example:

Object obj = (obj != null) ? obj : new Object();

Easy way to initialize an object if it's null.

Tudor
  • 61,523
  • 12
  • 102
  • 142
4

(statement) ? TRUE : FALSE

Example in pseudocode: a = (5 > 3) ? 1 : 0

If the statement is true, a will be one (which it is), otherwise it will be 0.

2

That's called a ternary operator, and it's a cute, if sometimes hard to read, way of writing an IF statement.

   if ( x == 3) {
      do-magic
   }
    else {
      do-other-magic
   }

would be expressed like so:

   x == 3 ? do-magic : do-other-magic
Nick Coelius
  • 4,668
  • 3
  • 24
  • 30
  • man tell me about it. I didn't understand the whole code just because of this ternary operator – Sobiaholic Dec 19 '11 at 20:03
  • so `?` simply means `if` – Sobiaholic Dec 19 '11 at 20:06
  • Essentially, yes. It is most often used for assignment, as @ExtremeCoder detailed, but can occasionally be used for logic in much the same way as an IF statement. Just wait until you start seeing nested ternary operators! – Nick Coelius Dec 19 '11 at 20:46