Decision & Braching

There are two types of decision making statements in Java. They are:

  • if statements
  • switch statements

The if Statement:

An if statement consists of a Boolean expression followed by one or more statements.

Syntax:

if(Boolean_expression)
  {
  //Statements will execute if the Boolean expression is true
  }

Example:

PROGRAM-1 : PROGRAM TO COMPUTE THE POSITION OF STUDENT ACCORDING TO PERCENTAGE OF MARKS?
Note: create a java file prog2.java

/*PROGRAM TO COMPUTE THE POSITION OF STUDENT 
 ACCORDING TO  PARCENTAGE OF MARKS ...*/
import java.io.*;
public class prog2 {
    public static void main(String[] args)throws IOException  {
		int  m;
		BufferedReader bf=new BufferedReader
			(new  InputStreamReader(System.in));
		System.out.println("ENTER YOUR MARKS  :: ");
		m=Integer.parseInt(bf.readLine());
		if(m>100){
			System.out.println("ENTER  CORRECT MARKS   
 				( MARKS  SHOULD BE BETWEEN 0 - 100 )..");
		}
		else if(m<100 && m>=80){
			System.out.println("YOU  ARE HONURS... ");
		}
		else if(m<80 && m>=75){
			System.out.println("YOU  ARE IN DICTANTION ... ");
		}
		else if(m<75 && m>=60){
			System.out.println("YOU  gain first division   ... ");
		}
		else if(m<60 && m>=45){
			System.out.println("YOU  ARE SECOND .. ... ");
		}
		else if(m<45 && m>=33){
			System.out.println("THIRD DIVISION  ..... ");
		}
		else{
			System.out.println("FAILD .. ");
		}
			
	}

}
        

The switch statement:

A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each case.

Syntax:

switch(expression){
    case value :
       //Statements
       break; //optional
    case value :
       //Statements
       break; //optional
    //You can have any number of case statements.
    default : //Optional
       //Statements
}

Example:

PROGRAM-6 : SIMPLE PROGRAM OF SWITCH - CASE statement

/*    SIMPLE PROGRAM OF SWITCH - CASE  */

import java.io.*;
public class prog4 
{
public static void main(String[] args) throws Exception 
{
int n;
BufferedReader bf=new BufferedReader
(new InputStreamReader(System.in));
System.out.println("(1)SOFTWARE ENGINEER \n(2)ELECTRONIC 
					ENGINEER \n(3)ELECTRICAL ENGINEER ");
System.out.println("ENTER YOUR CHOICE  : ");
n=Integer.parseInt(bf.readLine());
switch(n)
{
	case 1:
	{
		System.out.println("YOU CHOICE IS SOFTWARE ENGINEER ");
		break;
	}
	case 2:
	{
		System.out.println("YOU CHOICE IS ELECTRONIC  ENGINEER ");
		break;
	}
	case 3:
	{
		System.out.println("YOU CHOICE IS ELECTRICAL  ENGINEER ");
		break;
	}
	default :
	{
	System.out.println("YOU HAVE ENTER WRONG CHOICE  \n THANK YOU ..");
	break;
	}
}
}

}