In Java if... Tutorial on using else statements

  • 2020-04-01 04:21:31
  • OfStack

If statement
An if statement contains a Boolean expression and one or more statements.
grammar
The syntax of If statement is as follows:
If (Boolean expression)
{
    / / statement to be executed if the Boolean expression is true
}
If the Boolean expression is true, the code block in the if statement is executed. Otherwise, execute the code behind the If statement block.


public class Test {

  public static void main(String args[]){
   int x = 10;

   if( x < 20 ){
     System.out.print(" This is a  if  statements ");
   }
  }
}

The results of compiling and running the above code are as follows:


 This is a  if  statements 

The if... Else statements
The if statement can be followed by the else statement, and the else block is executed when the Boolean expression of the if statement is false.
grammar
The if... Else can be used as follows:
If (Boolean expression) {
    / / if the Boolean expression is true
} else {
    / / if the Boolean expression is false
}
The instance


public class Test {

  public static void main(String args[]){
   int x = 30;

   if( x < 20 ){
     System.out.print(" This is a  if  statements ");
   }else{
     System.out.print(" This is a  else  statements ");
   }
  }
}


The simplest example of an if-else statement

            Suppose I go to the office and ask huang wenqiang if he is in? If he would say yes when he was in, and an enthusiastic colleague replied "he is not in" when he was out, I would not immediately understand. Let's simulate it with a program:


public class demo { 

public static void main(String[] args) { 

//Set huang wenqiang not in

boolean flag = false; 

System.out.println(" start "); 

if (flag){ 

System.out.println(" in "); 

}else{ 

System.out.println(" He is not "); 

} 

System.out.println(" The end of the "); 

} 

}


Related articles: