The if statement in Java is utilized to evaluate a condition that is either true or false. There are several types of if statements that can be used in Java to create conditional statements with different outcomes based on the evaluated condition.
- if statement
- if-else statement
- if-else-if ladder
- nested if statement
if Statement in Java:
In Java, the if statement is utilized to verify a specific condition. If the condition evaluates to true, the if block of code is executed.
Syntax:
if(condition){ //code to be executed }
Example:
//Java Example Program to demonstate the use of if statement. public class IfExample { public static void main(String[] args) { //defining an 'age' variable int age=20; //checking the age if(age>15){ System.out.print("Age is greater than 15"); } } }
Output:
Age is greater than 15
if-else Statement in Java:
In Java, the if-else statement is used to assess a condition. It executes the if the block of code if the condition is determined to be true. However, if the condition is found to be false, the else block of code is executed.
Syntax:
if(condition){ //code if condition is true }else{ //code if condition is false }
Example: