Conditional Statements

To write useful programs, we almost always need to check conditions and change the behavior of the program accordingly. Conditional statements give us this ability. The simplest form is the if statement:

  if (x > 0) {
    System.out.println("x is positive");

The expression in parentheses is called the condition. If it is true, then the statements in brackets get executed. If the condition is not true, nothing happens.

The condition can contain any of the comparison operators, sometimes called relational operators:

  x == y // x equals y
  x != y // x is not equal to y
  x > y // x is greater than y
  x < y // x is less than y
  x >= y // x is greater than or equal to y
  x <= y // x is less than or equal to y

Although these operations are probably familiar to you, the syntax Java uses is a little different from mathematical symbols. Remember that = is the assignment operator, and == is a comparison operator. Also, there is no such thing as =< or =>.

The two sides of a condition operator have to be the same type. You can only compare ints to ints and doubles to doubles.

The operators == and != work with Strings, but they don't do what you expect. And the other relational operators don't do anything at all. We will see how to compare strings later.