JAVA Decision Making



DECISION
MAKING STATEMENTS

SELECTION STATEMENTS
The selection statements allows us to choose the set of instructions for execution depending upon an expression’s truth value. They are also known as decision making statements.

If-STATEMENT

SYNTAX:
if(condition)
{
 Instructions;
}

Here the instructions are executed only when the condition evaluates to be true.

If else –STATEMENT

SYNTAX:
if(condition)
{
 Instructions1;
}
else
{
 Instructions2;
}
Here Instruction1 gets executed if the condition evaluates to be true otherwise it Instructions2 gets executed.



THE switch STATEMENT
Java provides a multi-branch selection statement known as switch statement. It tests the value of an expression against a list of INTEGER or CHARACTER constants.

SYNTAX:

switch(expression)
{
 case constant1 : statement1
    break;
 case constant2 : statement2
    break;
 :
 :
 :
 case constant n: statement n
    break;
 default: default statement;
}

 Here break is a jump statement which when encountered provokes the compiler to jump to the next line of code. There are other jump statements too which we will discuss later.
‘default’ case is optional, if missing, no action takes place if none of the cases match.






DIFFERENCE BETWEEN SWITCH AND IF ELSE
               SWITCH
·       switch can test for equality only.
·        
·       Selects its branches by testing the value of the same variable against a list of constants.
·        
·       switch cannot handle ranges  
·        
·       It can handle integral or character values only.
                    IF-ELSE
  • if can evaluate relational and logical expressions.
  •  
  • Lets you use a series of expressions containing complex expressions.
  •  


  • It can handle ranges.
  •  
  • It can handle float values.





No comments:

Post a Comment