Previous | Home | Next |
The if statement is Java’s conditional branch statement. It can be used to route program execution through two different paths. An if statement consists of condition followed by one or more statements. If the condition evaluates to true then the block of code inside the if statement will be executed.
syntax :
if(condition) { statement; //Statements will execute if the condition is true }
Example :
class Max4 { public static void main(String args[]) { int a,b,c,d,max; a=5; b=10; c=30; d=15; max=a; if(b>max) { max=b; } if(c>max) { max=c; } if(d>max) { max=d; } System.out.print("max is "+max); } }
output :
30
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
synatx :
if(condition) { true statement; //Executes when the condition is true } else { false statement; //Executes when the condition is false }
Example :
class EvenOdd { public static void main(String args[]) { int n; n=6; if(n%2==0) { System.out.print("Number is Even"); } else { System.out.print("Number is odd"); } } }
output :
Number is Even
Previous | Home | Next |