Skip to main content

Java: if-else statement

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
Submitted by arilio666 on October 21, 2021

Ashwin is working with iVagus as a Technical Lead. He has experience in various technologies like Cypress, JavaScript, TypeScript, Rest Assured, Selenium, Cucumber, and Java.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.