There is only one type of if statement. The other is a conditional expression. As for which is better: they can compile into the same bytecode, and I expect them to behave the same way - or so close that you definitely won't want to choose one of them in terms of performance.
Sometimes an if will be more readable, sometimes a conditional statement will be more readable. In particular, I would recommend using a conditional operator when two operands are simple and free from side effects, whereas if the main purpose of these two branches is their side effects, I would probably use the if .
Here is an example program and bytecode:
public class Test { public static void main(String[] args) { int x; if (args.length > 0) { x = 1; } else { x = 2; } } public static void main2(String[] args) { int x = (args.length > 0) ? 1 : 2; } }
The bytecode is decompiled using javap -c Test :
public class Test extends java.lang.Object { public Test(); Code: 0: aload_0 1: invokespecial #1 4: return public static void main(java.lang.String[] Code: 0: aload_0 1: arraylength 2: ifle 10 5: iconst_1 6: istore_1 7: goto 12 10: iconst_2 11: istore_1 12: return public static void main2(java.lang.String[ Code: 0: aload_0 1: arraylength 2: ifle 9 5: iconst_1 6: goto 10 9: iconst_2 10: istore_1 11: return }
As you can see, there is a slight difference in the bytecode - istore_1 won or not (unlike my previous extremely erroneous attempt :), but I would be very surprised if JITTER ended up with another native code.
Jon Skeet Jan 16 '11 at 17:02 2011-01-16 17:02
source share