Java Online - Decision making, Branching & Looping

Programming languages or concepts

 
Decision making, Branching & Looping in Java Programming language

in this lesson we are learning Decision making & Branching in Java Programming. now lets go,

 Decision making structures have one or more conditions to be evaluated or tested by the program, along with a statement or statements that are to be executed if the condition is determined to be true, and optionally, other statements to be executed if the condition is determined to be false.

 Decision Making in Java topic is fairly self explanatory. Decision making means the action of taking decisions and choosing the action plan accordingly.

 

Decision Making in Java:

Decision making in Java executes a particular segment of code based on the result of a boolean condition.It is important because conditions define the flow of programs and the output of a particular program.

The decision making principles in Java chiefly consist of if else statements, continue, break and switch statements. It decides the flow of the program control during the execution of the program.

There are the 6 ways of exercising decision making in Java:

1. if
2. if-else
3. nested-if
4. if-else-if
5. switch-case
6. jump-break,continue,return


1. If Statement in Java:-

        Java if statement is the simplest decision making statement. It encompasses a boolean condition followed by a scope of code which is executed only when the condition evaluates to true. However if there are no curly braces to limit the scope of sentences to be executed if the condition evaluates to true, then only the first line is executed.

  Syntax:

if(condition)
{
//code to be executed
}


Flow Chart :-




Example:-
 

 // Java program to illustrate If statement

class Demo{
public static void main(String args[])
{
int age = 18;

if (age=16){
System.out.println("age is greater than 18");

}
           }
}


Output: 
 age is greater than 18

2. if else statement in Java:

      The if statement alone tells us that if a condition is true it will execute a block of statements and if the condition is false it won’t. But what if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false.

Syntax:-

 if(condition)
{
    //code to be executed if the condition is true
}
else
{
    //code to be executed if the condition is false
}

Example:-


Example:- 
 Program to write odd and even number.

// Java program to illustrate if-else statement
class IfElseEx
{
public static void main(String args[])
{
int i = 10;

if (i  % 2== 0)
System.out.println("even number");
else
System.out.println(" odd number");
}
}

3.  if-else-if Statements in Java:

            These statements are similar to the if else statements . The only difference lies in the fact that each of the else statements can be paired with a different if condition statement. This renders the ladder as a multiple choice option for the user. As soon as one of the if conditions evaluates to true the equivalent code is executed and the rest of the ladder is ignored.

Syntax:

if
{
        //code to be executed
}
else if(condition)
{
         //code to be executed
}
else if(condition)
{
         //code to be executed
}
else
{
        //code to be executed
}



Flow Diagram of Java if else if statements



Example:-

class IfElseLadderEx {
    public static void main(String[] args) {

        int examscore = 90;
        char grade;

        if(examscore >= 90) {
            grade = 'A';
        } else if (examscore >= 80) {
            grade = 'B';
        } else if(examscore >= 70) {
            grade = 'C';
        } else if(examscore >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }
        System.out.println("Grade is = " + grade);
    }
}


Output:-

          Grade is= A


4) Nested if Statements in Java:-


 A nested if is an if statement that is the target of another if or else. Nested if statements means an if statement inside an if statement. Yes, java allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement.

Nested if’s are important if we have to declare extended conditions to a previous condition.

Syntax:-
 
if(condition)
{
//code to be executed

if(condition)
{
//code to be executed
}
}



Flow diagram of Java nested if statement:-


Example:-

  1. public class Main
  2. {
  3. public static void main(String[] args) {

  4.         
  5.         int a = 25;
  6.     
  7.         if(a < 100){
  8.         if(a < 50){
  9.            System.out.println("a is less than 50");
  10.         }
  11.         if(a >= 50){
  12.            System.out.println("a is greater than 50");
  13.         }
  14.         }
  15.     
  16. }
  17. }


a is less than 50


5) Switch Statement in Java:-

    The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.

Points to Remember

  • There can be one or N number of case values for a switch expression.
  • The case value must be of switch expression type only. The case value must be literal or constant. It doesn't allow variables.
  • The case values must be unique. In case of duplicate value, it renders compile-time error.
  • The Java switch expression must be of byte, short, int, long (with its Wrapper type), enums and string.
  • Each case statement can have a break statement which is optional. When control reaches to the break statement, it jumps the control after the switch expression. If a break statement is not found, it executes the next case.
  • The case value can have a default label which is optional.

Syntax:

switch(expression)
{
case <value1>:
    //code to be executed
break;
case <value2>:
    //code to be executed
break;
default:
    //code to be default executed
}

Flow Diagram of Java switch statement:



Example:-

class SwitchCaseDemo
{
    public static void main(String args[])
    {
        char Choose= ch;
        switch (ch)
        {
        case 0:
            System.out.println(" ice cream");
            break;
        case 1:
            System.out.println(" Mango ice Cream");
            break;
        case 2:
            System.out.println("chocolate .");
            break;
        default:
            System.out.println(" Nothing .");
        }
    }
}

Output:-

Nothing .


6) Jump Statements in Java:-


        The jump statements are the keywords in Java which have specific meaning and specific action of disrupting the normal flow of the program.
       Some of them are:
        Java supports three jump statement: break, continue and return. These three statements transfer control to other part of the program.
  

 Java break statement:

            in java break statement is used for 
  • To exit a loop.
  • Used as a “civilized” form of goto.
  • Terminate a sequence in a switch statement
a. break statement as a goto statement
        
If we mention a label after the break keyword, the control shifts to the end of the particular label scope. Java prohibits the use of goto statements because it encourages branched behaviour of programming. However break labels function like goto statements.


Java program to illustrate the use of break keyword:
import java.util. * ;
public class IfStatEX {
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
      System.out.println(i);
      if (i == 5) break;
    }
  }
}
Output:-
0
1
2
3
4
5

Flowchart of Java break statement:





b. Continue Statement in Java

            Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such an action.


Java program to the use of the continue statement:
import java.util. * ;
public class ContinueStatement {
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {

      if (i == 5) continue;
      System.out.println(i);

    }
  }
}
Output:
0
1
2
3
4
5
6
8
9


Flow Diagram for Java continue statement:



c. Return Statement in Java:-


This keyword, when executed by the compiler, returns the control back to the method it was called from. This is generally used in methods which are not of the void type and return some values. When the statement is executed, the return function returns to the caller method along with whatever variable is mentioned in the definition.

Syntax:

return <value>;
or
return:



Java program to illustrate the use of the return statement in Java:

import java.util. * ;
public class ReturnStatement {
  static int funcsqr(int x) {
    return x * x;
  }
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {

      int y = sqr(5);
      System.out.println("The value returned by the function is " + y);
      return;
      // System.out.println("This statement would never get executed. ");
    }
  }
}



Tags:
close