Anna Wierciak

One of the most powerful features of computers is the ability to do different things based on different conditions – user input, data in a file – but how is this done in a program?

There are a few ways, one of the most popular and easiest to understand and use is an “if” statement. “if” statement consists of 3 parts: a condition that is evaluated, a sequence of operations that are executed if the condition is true, and a sequence of operations that is executed if the condition is not true.

if (something) {
   // Do this if something is true
} else {
   // Do this if something is not true
}

For example:

int i = 5;
int j = i*i*i;
if (j < 100) {
    System.out.println("5 cubed is less than 100");
} else {
    System.out.println("5 cubed is more than 100");
}

Exercise

Runs this code block inside your program. What is the result?


The “else” part is actually optional. You can write just this:

int i = 5;
int j = i*i*i;
if (j < 100) {
    System.out.println("5 cubed is less than 100");
}

In this case the output will only happen if the result of 5 cubed is less than 100. Otherwise nothing will be printed.


Exercise

Run this code block. Is anything printed?


The expression that we test is usually of a kind “left side” “comparison operator” “right side”. For example “i < j”, or “k > l”, or “k * 3 < f + j * 35”. There is a special case for equality. Because we use equal sign (“=”) to assign a variable a value (“i = 5”), we need another way to compare variables without writing to memory. So the equality operator is written as “==”. So to test if “i” is equal to 5, we write…

if (i == 5) {
    // Do something if "i" is 5"
}

Exercises

Write code that tests if “i” is 1 and output “one” if this is the case. Run the code with “i” being 1 and then again with “i” being 2.

Write code that prints the digit value of “i” in human language, i.e. if “i” is 1, it will print 1, if “i” is 2, it will print 2, and so on until (and including 9).