Java Tutorials: If Statements

In this tutorial I will discuss if statements and how they can be used to implement decision making in your programs.

First of all lets have a look at an example of an if statement. This will show you the syntax in Java.

Just by looking at the code listed above it should be pretty obvious as to what the code does. It checks the value of the variable called age, if this is greater than or equal to 18 it prints “You are an adult”, and if it is less than 18 “You are a minor” will be printed.

This shows the general structure of an if-else statement in java:

A useful feature of if statements in java is that you can nest them together to form complex decision making statements. The syntax of this is listed below.

Finally for this tutorial I am going to go through some special ways of using if statements and conditions. They are explained below

This statement means if the condition is NOT true. eg if (!(age==18)) means if the value of age is not 18

This statement means if condition 1 AND condition 2 are true. For example if ((if age>=18) && (gender.equals(“male”))) translates to if age is greater than or equal to 18 and the value of the string gender is maleThe .equals(String) method is used for testing if 2 strings are equal, all other variable types use ==.

This statement is very similar to the above one except that the || means OR. So the statement translates to if condition1 OR condition2 are met