Tuesday, October 20, 2015

Comparison between Switch and If-Else: JAVA

The switch and if-else both are selection statements and they both let you select an alternative out of given many alternative out of given many alternatives by testing an expression. However, there are some differences in their operations.

Here are some of those differences listed:

  • Switch statement differs from if statement in that switch can only test for equality whereas if can evaluate a relational or logical expression i.e. multiple conditions.
  • Switch statement selects its branches by testing the value of same variable (against a set of constants) whereas the if-else construction lets you use a series of expressions that may involve unrelated variables and complex expressions.
  • If-else is more versatile of the two statements. For instance, if-else can handle ranges whereas switch cannot. Each switch case label must be a single value.

    If(a>9 && a<15)
    Statement;

    But in case of switch we have to write 9 to 15 per cases.
  • If-else statement can handle floating-point tests also apart from handling integer and character tests whereas a switch cannot handle floating-point tests. The case labels of switch must be an integer byte, short, int or a char.
  • The switch case label value must be a constant. So, if two or more variables are to be compared, us if-else.
  • The switch statement is more efficient choice in terms of code used in a situation that supports the nature of switch operation (testing a value against a set of constants).
When we discuss these differences with an example then we can find some more explanation about if-else and switch statement. Each difference may have an example itself so write a program and make these differences. In the next article we will learn about nested switch.

No comments:

Post a Comment