What's the main difference between Switch and If comparison in java ?
What's the main difference between "Switch" and "If" comparison
Switch differs from if statements in the following way:
Switch can only test for equality, whereas it can evaluate any type of Boolean expression. That is, the switch looks only for a match between the value of the expression and one of its case constants Switch statements are more efficient that if statements.
When Java compiler compiles a switch statement it looks at the case constants and creates a jump table that it will use for selecting the path of execution depending on the value of the expression. So if you are comparing large group of values switch will be faster than sequence of if-elses. Compiler knows that the case constants are all the same type and simply must be compared for equality with the switch expression. The compiler has no such knowledge of a long list for if expressions.
In the below code snippet we are displaying the number in words. If its "1" then display "one" and if its "2" display "two. For "if" condition it scans through the entire if" conditions but in switch statement it directly jumps to the logic after looking at the lookup table.
difference between Switch and if else statement
Tags:
Learn Java Programming