First of all let's pretend we want the user to guess a secret number. If the number is too big then we want to display a dialog box saying "Sorry dude, your choice is too big". If the number is too small, then we want to say "Sorry dude, your choice is too small". Finally, if they guess the number then we should say "Hurrah! You got it!".

This can be done using a special construct called if - then - else. The if statement has the following syntax in Java. It is also known as a control statement as it changes the flow of a program.

  1. If ( <Condition>) {
  2. //code is placed here
  3. }

The condition is a test which must evaluate to true of false. If the condition is true then we run the code inside the if statement. Otherwise we do nothing.

  1. If (4 == 4) {
  2. System.out.println("4 = 4. We have a genius on our hands here!") ;
  3. }

The above code shows a simple example of a conditional test. We are testing to see if the number 4 equals the number 4. Clearly it does, so we run the code held inside the If statement. Anything which is in between the { and } will be run if the condition turns out to be true. The funny {} symbols (called curly brackets) allows us to create blocks of code. See the section on code blocks for more info.

Notice that we have the condition 4 == 4. In the last section we saw that the equals sign, =, is the assignment operator and used to assign values to variables. Java tells the difference by using a double == to show equals. Yeah go figure.

next else >>

 
Basics
Menu
Search