Font Awesome Icons

Tutorial

if statement in java

Simple if statement is the basic of decision-making statements in Java. It decides if certain amount of code should be executed based on the condition.​

Example:

class if1
{
public static void main(String args[])
{
int x = 5;
if (x > 10)
System.out.println(“Inside If”);
System.out.println(“After if statement”);
}
}

if…else Statement

In if…else statement, if condition is true then statements in if block will be executed but if it comes out as false then else block will be executed.

class if2
{
public static void main(String args[])
{
int x = 9;
if (x > 10)
{
System.out.println(“x is greater than 10”);
}
else
{
System.out.println(“x is less than 10”);
}
System.out.println(“After if else statement”);
}
}

Nested if statement:

Nested if statement is if inside an if block. It is same as normal if…else statement but they are written inside another if…else statement.

class nestedif
{
public static void main(String args[])
{
int x = 25;

if (x > 10)
{
if (x%2==0)
System.out.println(“x is greater than 10 and even number”);
else
System.out.println(“x is greater than 10 and odd number”);
}
else
{
System.out.println(“x is less than 10”);
}
System.out.println(“After nested if statement”);
}
}

if...else if…else statement:

if…else if statements will be used when we need to compare the value with more than 2 conditions. They are executed from top to bottom approach. As soon as the code finds the matching condition, that block will be executed. But if no condition is matching then the last else statement will be executed.

class ifelseif
{
public static void main(String args[])
{
int x = 2;

if (x > 10)
{
System.out.println(“i is greater than 10”);
}
else if (x <10)
System.out.println(“i is less than 10”);
}
else
{
System.out.println(“i is 10”);
}
System.out.println(“After if else if ladder statement”);
}
}