Website For Developers

IF-ELSE statement in Java



if statement

Syntax

if (Boolean_expression)
{
// Executes if Condition is true
}


Example of if statement in Java

public class IfStatement{

   public static void main(String[] args) {
     if(2+2==4){
       System.out.print( "Condition is true!" );
     }
   }
}

Output

Condition is true!



if-else statement in Java

Syntax

if (Boolean_expression) {
// Executes if Condition is true
}
else {
// Executes when Condition is false
}


Example of if-else statement in Java

public class IfElseStatements{

   public static void main(String[] args) {
     if(2+2==5){
       System.out.print( "Condition is true!" );
     }
     else{
       System.out.println( "Condition is false!" );
     }
   }
}

Output

Condition is false!


Q: Write a program to take number from user and find the number is Even or Odd with the help of if-else statement in Java.

import java.util.Scanner;
public class EvenOdd {

   public static void main(String[] args) {
     Scanner scan = new Scanner(System.in);
     int number;

     System.out.print( "Enter an Integer: " );
     number = scan.nextInt();

     if(number%2==0){
       System.out.println(number+" Is an even number." );
     }
     else{
       System.out.println(number+" Is an odd number." );
     }
   }
}

Output

Enter an Integer: 13
13 Is an odd number.