Selection statements
The selection statements have four variations:
if
statementif...else
statementif...else if-...-else
statementswitch...case
statement
if
The simple if
statement allows executing a certain statement or block conditionally, only when the result of the expression evaluation is true
:
if(booelan expression){ //do something }
Here are a few examples:
if(true) System.out.println("true"); //1: true if(false) System.out.println("false"); //2: int x = 1, y = 5; if(x > y) System.out.println("x > y"); //3: if(x < y) System.out.println("x < y"); //4: x < y if((x + 5) > y) { //5: x + 5 > y System.out.println("x + 5 > y"); x = y; } if(x == y){ //6: x == y System.out.println("x == y"); }
Statement 1 prints true
. Statements 2 and 3 print nothing. Statement 4 prints x < y
. Statement 5 prints x + 5 > y
. We used braces to create a block because we wanted the x = y
statement to be executed...