mercredi 4 septembre 2013

if else != :? ... a bit weird but let me explain


in a lot of tutorial you might see that the the ternary operator ?: is similar to an if ... else statement
A lot of tutorial are wrong on this subject
Trust me !
euh not just trust yourself ... and the compiler ... and the offical doc


the basic : 

?: operartor is very similar to if else


public class dummy {
 
 public static int f1_int() {return 1;}
 public static int f2_int() {return 2;}

 public static void main (String [] args)
 {
 boolean b = true;
 // this line
 int a = b?f1_int():f2_int();
 // is similar to this one
 if (b) { a = f1_int();} 
 else { a = f2_int();}
 }
}


But not fully : First Difference
?:  can be use only for assignment  !
not convinced , remove the assignment in the ?:
  • From :    int a = b?f1_int():f2_int(); 
  • To :    b?f1_int():f2_int();
it does not compile anymore : (

this brings some consequence  when you write condition?expression1:expression2
  • expression1 and expression2 cannot return void.
  • expression1 and expression2 must be "compatible" in term of type ( boxing , inheritance etc )

The last condition is not so simple . here is the full and official description that you can trust
here is the link to the official specification of the operator ?:
http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25

for instance look on this tricks , what is the result  ?


public class dummy {

 
 public static int f(Object o) { return 1; }
 public static int f(Integer o) { return 2; }
 

 public static void main (String [] args)
 {
 boolean b = false;
 int a =  f(b?new Object():new Integer(44));
 
 System.out.println(a);
 }
}

this displays 1, even if b is false. You might believe that f(Integer) will be called but not
it is because the first operand has been detected as Object and the second will be assumed as Object too

if you do that using if , you will not have the same result

Aucun commentaire:

Enregistrer un commentaire