Java’s If Statement in Five Minutes

Conditional statements are fundamental for imperative programming languages, including Java. They‏re used to instruct a program to act differently based on whether something is true or false. Java‏s if statement is the most basic conditional statement   it evaluates a boolean expression and executes code based on its outcome.

To follow along, you need to have a basic understanding of equality, relational, and conditional operators and how to form boolean expressions with them. You should be good to go if you get why 1 > 0 evaluates to true and num == 5 evaluates to false when num equals anything other than 5.

The if Statement

The if statement is the most fundamental control flow statement. Once you understand it, the others will come easily. Essentially, an if statement tells a program to execute the following block of code only if the accompanying condition is true.

Here you can see the anatomy of an if statement:

int num = 5;    if (num == 5) {      System.out.println("This message gets printed because num is 5.");  }  

A variable num is declared and set to 5. What comes after that is the if statement.

It starts with the keyword if followed by a pair of parenthesis. Between the parenthesis you need to provide a condition. A condition is a boolean expression   something that evaluates to either true or false. It can be a variable of type boolean, equality, relational, or conditional expressions (like num == 5), or even a method call that returns a boolean. Boolean object wrappers are also valid.

After the parenthesis you can see a pair of curly braces defining a block of code, often called the if block or if branch. That code is only executed if the condition evaluated to true.

It is common practice to indent your if block as it provides a visual hint for readers. For code blocks that contain only a single line of code you can omit the curly braces   whether you should is a different discussion.

The if-else Statement

Continue reading %Java‏s If Statement in Five Minutes%

You may also like...