The format of an if-else statement is
if (condition) statement1 else statement2
The condition must be a Boolean expression, which evaluates to true or false.
If the condition evaluates to true, statement1 is executed. Otherwise, statement2 is executed.
The else part is optional. You may write a statement as
if (condition)
statement1
The following code checks the num1 value range.
int num1 = 20; int num2 = 30; if (num1 > 50) num2 = num2 + 10; else num2 = num2 - 10;
public class Main { public static void main(String[] args) { int num1 = 20; int num2 = 30; if (num1 > 50) num2 = num2 + 10;// w ww . ja v a 2 s . com else num2 = num2 - 10; System.out.println("num2 = " + num2); } }
You can bundle two statements into one block statement.
if (num1 > 50) { num2 = num2 + 10; num3 = num3 + 10; } else { num2 = num2 - 10; num3 = num3 - 10; }
public class Main { public static void main(String[] args) { int num1 = 20; int num2 = 30; int num3 = 40; if (num1 > 50) { num2 = num2 + 10;// w w w . java2s. c o m num3 = num3 + 10; } else { num2 = num2 - 10; num3 = num3 - 10; } System.out.println("num2 = " + num2); System.out.println("num2 = " + num3); } }