if Statement in Java Programming
Decision Making in Java
In this lesson, we will understand what if statement is and how to use it in Java programming along with some example.
What is if Statement
The if statement is the most simple decision making statement in Java programming. Using if statement we test some condition, if the condition is true then a block of statements is executed otherwise not.
if Statement Syntax
if(condition)
{
/* Statements to execute if
condition is true */
}
In the above syntax inside the brackets ( ) of if statement we will write our condition. If the condition is true then the statements written within the curly braces { } of if statement will execute otherwise not. We can write our condition using Arithmetic, Relational and Logical operators.
Now let's see some examples for more understanding.
Example 1 (Condition using Relational operator)
Java program to check if an integer variable's value is greater than 10.
public class Example
{
public static void main(String args[])
{
int a=25;
if(a>10)
{
System.out.println("Yes " + a + " is greater than 10");
}
}
}
Output
Yes 25 is greater than 10
Here you can see that the condition (a>10) is true because the value of a is greater than 10. So the statement which is written inside the curly braces of if statement has executed and the output is printed on the screen.
Example 2 (Condition using Arithmetic and Relational operator)
Java program to check if the sum of 2 integer variable's value is greater than 10.
public class Example
{
public static void main(String args[])
{
int a=10, b=5;
if(a+b>10)
{
System.out.println("Yes " + (a+b) + " is greater than 10");
}
}
}
Output
Yes 15 is greater than 10
Here you can see that we have used Arithmetic and Relational operator in the condition (a+b>10) and the condition is also true because the value of a+b is greater than 10. So the statement which is written inside the curly braces of if statement has executed and the output is printed on the screen.
Example 3 (Condition using Arithmetic, Relational and Logical operator)
Java program to check if an integer variable's value is an even number and is also greater than 10.
public class Example
{
public static void main(String args[])
{
int a = 18;
if(a%2==0 && a>10)
{
System.out.println(a + " is an even number and is also greater than 10");
}
}
}
Output
18 is an even number and is also greater than 10
Here you can see that we have used Arithmetic, Relational and Logical operator in the condition (a%2==0 && a>10) and both the conditions a%2==0 and a>10 are also true because the remainder of the modulus division a%2 is equal to 0 and also value of a is greater than 10. So the statement which is written inside the curly braces of if statement has executed and the output is printed on the screen.