We use if in a program so that a piece of code may only be carried out under certain circumstances, which we can choose, by specifying some conditions that must be satisfied. It is one way in which the flow, the order in which lines of code are executed when the program runs, can be controlled, (you may find it helpful to think of if and other forms of flow control by imagining a flow chart). A basic example of the code for an if statement is as follows:
if ( boo ) { x = y; }In this short piece of code, x is only set equal to y if whatever condition we have chosen to put in the round brackets () is true. This is where the boolean variable type briefly mentioned earlier may come in useful. If the value of a boolean variable boo is true, he code in the curly brackets
{}
(in the above case
x = y) is executed. If boo is false, the code in
curly brackets {}
will not be executed.
Notice how within the curly brackets {}
code is indented. This
is simply to make it clearer that the code is contained within an
if statement.
More usefully for the scientist, we can write things like
if (w < z) { x = y; }As you might expect if (w < z) means `if w is less than z', and in the above code x = y only happens if it is true that w is less than z. It is also possible to use the same variables in the condition, i.e. between the round brackets (), as between the curly brackets
{}
if you need to.
Less than, <, is an example of a comparison operator -- it compares two variables, asking whether one is less than the other, returning a boolean result -- true if the condition is satisfied and false if it is not. The other comparison operators are in the table below. Note the difference of w == z i.e. `does w equal z?' to x = y i.e. `set the value of x equal to y' which is the assignment operator we met earlier.
Here's a simple example where if is used to compute the modulus, i.e absolute value, of any double value entered.
/** * Purpose: An example to demonstrate use of `if' */ import java.io.*; public class IfExample { public static void main(String[] args) throws IOException { //Read in a value from the keyboard BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.println("Enter positive or negative number..."); String temp = br.readLine(); double x = Double.parseDouble(temp); if ( x < 0 ) { x = -x; } System.out.println("The modulus of this number is " + x); } }