JAVA FLOW CONTROLS

FLOW CONTROL AND CLASSES

EXAMPLE IF

 
public class MyClass

 {

  public static void main(String[] args)

{

    if (20 > 18)

{

      System.out.println("20 is greater than 18"); // obviously

   } 

  }

}

OUTPUT

20 is greater than 18
IF ELSE
Use the else statement to specify a block of code to be executed if the condition is false.

Syntax

if (condition)
 {
  
// block of code to be executed if the condition is true
else
 {
  
// block of code to be executed if the condition is false
IF ELSE IF EXAMPLE

public class  gasc2
{
  public static void main(String args[])
  {
  int a=10;
  if(a==10)
  {
  System.out.println("gobi");
  }
  else if(a<10)
  {
  System.out.println("arts");
  }
  }
}
OUTPUT
GOBI
BREAK

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to "jump out" of a switch statement.
The break statement can also be used to jump out of a loop.
BREAK EXAMPLE

public class dog2
{
  public static void main(String args[])
  {
  int i;
  for(i=0;i<5;i++)
  {
  if(i==3)
  { 
  break;
  }
  System.out.println(i);
  }
  }
}
OUTPUT
0
1
2
CONTINUE

The continue statement breaks one iteration (in the loop).
if a specified condition occurs, and continues with the next iteration in the loop.
 CONTINUE EXAMPLE

public class dog2
{
  public static void main(String args[])
  {
  int i;
  for(i=0;i<5;i++)
  {
  if(i==3)
  { 
  continue;
  }
  System.out.println(i);
  }
  }
}
OUTPUT
0
1
2
4
SWITCH CASE

Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression) {
  case x:
    
// code block
    break;
  case y:
    
// code block
    break;
  default:
    
// code block
}
EXAMPLE SWITCH

int day = 4;
switch (day) {
  case 1:
    
System.out.println("Monday");
    break;
  case 2:
    
System.out.println("Tuesday");
    break;
  case 3:
    
System.out.println("Wednesday");
    break;
  case 4:
   
System.out.println("Thursday");
    break;
  case 5:
   
System.out.println("Friday");
    break;
  case 6:
   
System.out.println("Saturday");
    break;
  case 7:
   
System.out.println("Sunday");
    break;
}
// Outputs "Thursday" (day 4)
RETURN KEYWORD

The return keyword finished the execution of a method, and can be used to return a value from a method.
RETURN KEYWORD EXAMPLE

public class MyClass
 {
  static 
int myMethod(int x)
   {
     
return 5 + x;
    }

  public static void main(String[]
args)
 {
   
System.out.println(myMethod(3));
  }
}
 Outputs 8 (5 + 3)
VOID

The return keyword finished the execution of a method, and can be used to return a value from a method.
VOID EXAMPLE

public class MyClass
{
  static 
void myMethod()
  {
    
System.out.println("I just got executed!");
  }

  public static void main(String[]
args)
 {
   
myMethod();
  }

}
           


  

Comments