Flow Control in Java

Flow Control in Java

                                                        Flow Control

Flow control decides which order in the statement will be executed at runtime. that's called flow control.

  •  Selection statement
    • if-else
    • switch()
  • Iterative statement
    • while()
    • do-while()
    • for()
    • for-each()    1.5v
  • Transfer Statement
    • break;
    • continue
    • return 
    • try -catch finally
    • assert    1.4v
                                                                    Selection Statement
1-: if-else
The argument to the if statement should be boolean type by mistake trying to provide any other type we will get compile time error.



/*
                                                if-else syntax
if(b){
     statement if b is true
}else{
   Statement if b is false
}
*/
Examples-:
/*
Example-:1

  class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int x=0;
        if(x){
            System.out.println("hello");
        }else{
            System.out.println("hi");
        }
    }
}

Compile Errors :

error: incompatible types: int cannot be converted to boolean
        if(x){
           ^         
  location: class Test
1 errors

Example -:2

class Test
{
    public static void main (String[] args) 
    {
        int x=10;
        if(x=10){
            System.out.println("hello");
        }else{
            System.out.println("hi");
        }
    }
}

Compile Errors :

./Test.java:7: error: incompatible types: int cannot be converted to boolean
        if(x=10){
            ^
1 error
Example -:3

class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        int x=10;
        if(x==10){
            System.out.println("hello");
        }else{
            System.out.println("hi");
        }
    }
}

Output:

    Hello


Example -:4
class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        boolean x=true;
        if(x=false){
            System.out.println("hello");
        }else{
            System.out.println("hi");
        }
    }
}

Output:

             hi

Example-5
class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        boolean x=false;
        if(x==false){
            System.out.println("hello");
        }else{
            System.out.println("hi");
        }
    }
}

Output:

  Hello
*/

Important -:
  • else part and curly braces are optional without curly braces only on statements allowed under if which should not be a declarative statement.

  • There is no dangling else problem in java every else is mapped to the nearest if statement.
               /*
                        if(true)
                            if(false)
                                System. out.print("Hello");
                         else                                               //this else for second if 
                                System.out.print("hi");
                */
  • Note-: semicolon is a valid java statement which is also known as an empty statement.

/*
Examples-:

if(true)
   System.out.print("Hello");

Output

      Hello

if(true);

Output
     No Output

if(true)
  int x=20;

Compile Errors :

./Test.java:8: error: variable declaration not allowed here
            int x=20;
                ^
1 error


if(true)
{
   int x=20;
}

output

    No output



2-: switch(argument)
if several options are available then it is not recommended to use nested if-else because it reduces
readability to handle this required we should go for switch() statement.

/*
                                                   switch() syntax
switch(x){
   case 1:
             statement 1;
             break;
   case 2:
            statement 2;
            break;
            .
            .
            .
            .
  case n:
           statement n;
            break;
   default:
             statement; 
}
*/
  • The allowed argument type for switch statements are byte,short ,char,int until 1.4v but from 1.5v onward corresponding wrapper(Byte,Short,Character,Integer) classes and enum also allowed. from 1.7v onward Strings are allowed.
            

  • curly braces are mandatory except switch() everywhere curly braces are optional.
  • Both case and default are optional .
  • that is empty switch statement is valid in java syntax.
          Example-:
          /*
                int x=10;
                switch(x){
                }
          */
  • inside switch() every statement should be under some case are default that is independent statements not allowed inside switch(). otherwise, we will get a compile-time error.

         Example-:
          /*
               class Test
                {        
                        public static void main (String[] args) throws java.lang.Exception
                        {
                              int x=10;
                              switch(x){
                                      System.out.println("hello");
                              }
                        }
                }
                    

Compile Errors :

./Test.java:8: error: case, default, or '}' expected
          System.out.println("hello");
          ^
./Test.java:8: error: case, default, or '}' expected
          System.out.println("hello");
                ^
./Test.java:8: error: case, default, or '}' expected
          System.out.println("hello");
                 ^
./Test.java:8: error: case, default, or '}' expected
          System.out.println("hello");
                    ^
./Test.java:8: error: case, default, or '}' expected
          System.out.println("hello");
                     ^
./Test.java:8: error: case, default, or '}' expected
          System.out.println("hello");
                            ^
./Test.java:8: error: case, default, or '}' expected
          System.out.println("hello");
                             ^
./Test.java:8: error: case, default, or '}' expected
          System.out.println("hello");
                                    ^
./Test.java:8: error: case, default, or '}' expected
          System.out.println("hello");
          */
  • Every case label should be compile-time constant(that is constant expression).

          Example-:
          /*
            class GFG
            {
                public static void main (String[] args) throws java.lang.Exception
                {
                      int x=10;
                      int y=20;
                      switch(x){
                           case 10:
                          case y:
                   }
             }
         }
            

        Compile Errors :

./Test.java:10: error: constant expression required
          case y:
               ^
1 error
  • if we declare y as final we won't get any compile time error.
               
              Valid        
            class Test
            {
                public static void main (String[] args) throws java.lang.Exception
                {
                      int x=10;
                      final int y=20;
                      switch(x){
                           case 10:
                          case y:
                   }
             }
         }
       
*/

  • both switch and case labels can be expressions but case labels should be a constant expressions.
        Example-:
        /*
            int x=10;
            switch(x){
                case 10:
                        System.out.print(x);
                        break;
                case 10+20+30:
                         System.out.print(x);
                         break;
          }
       */
  • every case label should be in the range of switch() argument type otherwise we will get compile time error
         Example-:
        */
           byte b=10;
           switch(b){
               case 10:
               case 100:
               case 1000:
           }
          is invalid compile time error case 1000 loss of precision found in required int

          byte b=10;
          switch(b+1){
              case 10:
             case 100:
            case 1000:
       
       is valid

*/
  • duplicate case labels are not allowed otherwise we will get compile time error.
         Example-:
         int b=10;
          switch(b){
            -> case 97:
                case 98:
                case 99:
          ->  case 'a':
       } 

Case Label Summary


Fall Through inside switch()
within the switch () if any case is matched from that case onward all statements will be executed until the break or end  switch this is called fall through inside switch()
the main advantage of  fall through is we can define common action for multiple cases(code reusability)

Examples-:
/*
   int x=10;
   switch(x){
        case 1:
        case 2:
        case 3:
            System.out.print("Q-1");
            break;
    
        case 1:
        case 2:
        case 3:
            System. out.print("Q-2");
            break;
      default:
             System. out.print("def");
}
  
*/

/*
   switch(x){
        case 0:
               System. out.print(0);
        case 1:
                System.out.print(1);
                break;
        case 2:
            System. out.print(2);
      default:
             System. out.print("def");
}
  
output for different values of x
x=0             x=1               x=2        x=3
0                    1                   2            def
1                                        def    

       
*/

Default case-: within the switch() default case at most once default case will be executed if and only if there is no case matched. within the switch() we can write the default case anywhere but it is recommended to write it as the last case.

Example-:

/*
   switch(x){
         default:
             System. out.print("def");
        case 0:
               System. out.print(0);
               break;
        case 1:
                System.out.print(1);
        case 2:
            System. out.print(2);
      
}
  
output for different values of x
x=0             x=1               x=2        x=3
0                    1                   2            def
                      2                                  0    
*/

Previous Post Next Post

Most Recent