click here for complete presentation

if statements

The idea of an if

A very natural if-then sort of relationship
If the condition is true, then do something
For example:
If I win a million dollars,
Then I will yodel like an insane Swiss monkey

Any statement that evaluates to a boolean is legal

Examples:

  • x == y
  • true
  • (1 + 2) < 5
  • s.equals("Help me!") && (z < 4)

An if with multiple statements

if( condition )
{

statement1;
statement2;

...
statementN;

}

What if you need to do several things conditionally?

Use braces to treat a group of statements like a single statement
I would encourage you to use this style all the time!

if( x == 4 )
{

System.out.println("I dislike 4");
System.out.println("Let us change x.");
x = 10;

}

Comparison

The most common condition you will find is a comparison between two things

In Java, that comparison can be:
==   equals
!=   does not equal
<   less than
<=   less than or equal to
>   greater than
>   =greater than or equal to

Equals

  • You can use the == operator to compare any two things of the same type
  • Different numerical types can be compared as well (3 == 3.0)
  • Be careful with double types, 0.33333333 is not equal to 0.33333332

Not Equals

  • Any place you can use the == operator, you can use the != operator
  • If == gives true, the != operator will always give false, and vice versa
  • If you want to negate a condition, you can always use the ! as a not

if( x != 4)

is the same as

if( !(x == 4) )

Greater Than (or Equal To)

Just like less than or equal to, except the opposite
Note that the opposite of <= is > and the opposite of >= is <

Thus,

!( x <= y ) is equivalent to ( x > y )
!( x >= y ) is equivalent to ( x < y )

If Statements

Credit: A Slides are modified with permission from Barry Wittman at Elizabethtown College
This work is licensed under an Attribution-NonCommercial-ShareAlike 3.0 Unsupported License