Menu
Coddy logo textTech

if-else Statement

Lesson 3 of 11 in Coddy's Control Statements in Java course.

Before this lesson, we studied the "Simple If" statement, which meant to run a particular code if a condition is true. Now,  what if I want to run a different code in both cases?

Example: If you are having a cold, you will have tea; otherwise, you will eat ice cream.

In Java, when you want to decide if this else that, then you use an if-else statement.

This statement evaluates the condition; if true, it executes one block of statements, and if false, it executes the else block of statements. ​

Syntax:​

if(condition)​
{​
    //code​
}​
else{​
   //code​
}​
challenge icon

Challenge

Easy

Write a function using if-else statement to accept  the number and check if the number is even or odd. 

Print the string accordingly as "Even" or "Odd".

Try it yourself

class IsEvenOdd {
    public static String IsEvenOdd(int a1) {
        // Write code here
    }
}

All lessons in Control Statements in Java

1What are Control Statements?

Introduction