Conditional Statement in Java

if statement in java, is a block of code which can be used to execute one or more statement on certain condition. if statement is also called as decision statement. or conditional statement in java. It can be followed by an optional else statement. It is always in the form Boolean expression which evaluates to true or false, if condition written in that statement / expression is true then if block code is executed, else block will be executed when condition is false.

If Statement -:
Syntax -;
if (expression)
{
Statement 1 ;
}
else
{
Statement 2 ;
}
Example -:
public class condloop {

public static void main(String[] args) {
// TODO Auto-generated method stub
int a = 15;
if(a<=10){
System.out.println( “a is small number” +a);
}
else
{
System.out.println(“In the else block”);
}
}
}
Output -:
In the else block

else if -:
If we have more than one condition to check we can use else if.
Syntax -;
if (expression)
{
statement 1 ;
}
else if (expression)
{
statement 2 ;
}
else
{
statement 3;
}.

Example -:
import java.util.Scanner;
public class ifelse {

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in=new Scanner(System.in);
System.out.println(“Enter value of a”);
int a=in.nextInt();
if(a<=10){
System.out.println(“number is small”);
}
else if(a>=11 && a<=50) {
System.out.println(“number is medium”);
}
else
System.out.println(“number is large”);
}

}

Output -;
Enter value of a
12
number is medium

Leave a Reply