What is difference between if statement and switch statement

What is difference between if statement and switch statement ?

Answer : Please see below :

if statement

switch statement

if can be used to test multiple conditions switch cannot be used to test multiple conditions
multiway execution is not available switch provides multiway execution
if statement is not good choice if number of condition is more. Because switch uses index mapping on variable choice to the corresponding solutions switch statement is preferable if number of test conditions are more
for multiple condition if statement is not developer friendly and including maintenance of code could be tough switch is generally more dense for multiple condition
in if statement you can evaluate complex expressions switch evaluate expression using constant
if statement accepts all data types switch statement accepts only primitive types as key and constants for cases
Performance of if statement will be slow for multiple condition Performance is faster because switch uses index mapping

 

Leave a Reply

Your email address will not be published. Required fields are marked *