Java: if-else statement

Profile picture for user arilio666

An If else statement is a control flow in a java programming language that conveys that anything that satisfies and is true to the logic provided will be able to execute the logic body.

  • If the condition is not satisfied the if┬ábody is rejected and the code continues for the else block which is the second body present for if statement to able to execute the second response of the satisfies.
  • To put it simply it's like either do this or that.

Syntax

If(Condition)
{
    //if the conditon is true this body will be executed
}
else
{
    //second alternative condition
}

Example

public class Test
{
    public static void main(String[] args)
    {
        int val1 = 15, val2 = 2, val3, val4 = 10, val5;
        
        if ((val2 + val1) == 18)
        {
            System.out.println("Correct Sum Up Here Is Your Token : " +val4);
        }
        else
        {
            System.out.println((val2 + val1));
        }
    }
}

Output: 17

Here I have told the condition of printing the if statement when val2 and val1 sum is equal to 18. Unfortunately, it is not 18. So, the else block gets executed instead and proceeds to execute the statement present within it.

Tags