if statement
An if statement contains a Boolean expression and one or more statements.
grammar
The syntax of the If statement is used is as follows:
if(boolean expression)
{
//Statement that will be executed if the boolean expression is true
}
If the value of 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 the if statement"); } }} The above code compilation and running results are as follows:
This is the if statement
if...else statement
The if statement can be followed by an else statement. When the Boolean expression value of the if statement is false, the else statement block will be executed.
grammar
If…else is used as follows:
if(boolean expression){
//If the value of the boolean expression is true
}else{
//If the value of the boolean expression is false
}
Example
public class Test { public static void main(String args[]){ int x = 30; if( x < 20 ){ System.out.print("This is the if statement"); }else{ System.out.print( "This is an else statement"); } }}
The simplest if-else statement example
Suppose I went to the office to ask if Huang Wenqiang is there? If he would say he was there, and when he was not there, an enthusiastic colleague answered "He is not here", then I would not understand immediately. Let's use the program to simulate it:
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.print ln("in" ); }else{ System.out.println("He is not here"); } System.out.println("End"); } }