Introduction to programming, Lesson 3


Have a basic understanding about how variables work? OK now lets move on to control structures. A control structure can be thought of as a 'decision' that the computer is required to make at a specific point in the code. Control structures are governed by a new type of native variable called a boolean variable. A boolean variable has only two possible values, 'true' and 'false'. Examine the following code fragment:

  public class Decisions
  {
      public static void main(String [] args)
      {
          boolean boolValue1 = true;
          boolean boolValue2 = false;
		  
          if (boolValue1 == true)
          {
              System.out.println("boolValue1 is true!");
          }			  
          else
          {
              System.out.println("boolValue1 is false!");
          }
		  
          if (boolValue2 == true)
          {
              System.out.println("boolValue2 is true!");
          }
          else
          {
              System.out.println("boolValue2 is false!");
          }
      }
  }
  

In the above program, each 'if' statement represents a decision the computer has to make. In this case, the decisions are easy and quite contrived, but the point is to demonstrate the concept. If we were to run this program, we would see that the computer found the variable called boolValue1 to have a value of 'true' and boolValue2 to have a value of 'false'. Nothing shocking here. Notice how there are 4 lines of System.out.print...... However, only 2 of them will be executed due to the nature of the decision process. The 'else' block of code will only be executed if its corresponding 'if' statement is false.

Have you noticed the use of the '=' sign and the '==' sign? Don't confuse the two! They mean entirely different things to the computer. When you use a single equal sign, '=', you are assigning a value to a variable. When you use a double equal sign, '==' you are comparing two values. Now examine this block of code that a sloppy programmer wrote:

  public class SloppyDecisions
  {
      public static void main(String [] args)
      {
          boolean varValue1 = true;
          boolean varValue2 = false;
		  
          if (varValue1 == true)
          {
              System.out.println("varValue1 is true!");
          }
          
          System.out.println("varValue1 is false!");
          
          if (varValue2 = true)
          {
              System.out.println("varValue2 is true!");
          }
      }
  }
  

If you run the above code, you'll find two contradicting statements! Both lines of code regarding varValue1 are written to the screen in an obvious error of judgement. What happened? The sloppy programmer forgot to write an else block around the second println statement! So the computer simply performed the next available instruction, without any evaluation process. Additionally, look at the second if statement. varValue2 = true actually assigns the value of true to varValue2 (see the single equal sign '='?), when clearly a comparison was called for. Thus, the code inside of the if block is executed, even though it was not intended!

You can use if statements to evaluate integers too. The following fragment is valid in a Java program:

  int myInteger = 5;
  
  if (myInteger == 5)
  {
      System.out.println("myInteger is 5!");
  }
  

Wait...I thought you said if statements were controlled by boolean values. I don't see any boolean values in the preceding code fragment. What gives? It turns out that Java will evaluate ANY expression inside of the if(...) statement. Behind the scenes, Java assigns a value of 'true' to the statement if it is, in fact, true, and 'false' otherwise. Remember, the code inside the if block only executes when the if(...) is evaluated as true.

There are other evaluation operators as well:

So, if I want to test if one variable is greater than another, I would write:

    int oneInteger = 780;
    double anotherNumber = 900.05;
    
    if (anotherNumber <= oneInteger)
    {
        // do something
    }
    else
    {
        // do something else   
    }
  

(The '//' in the above code indicates a comment. The computer ignores any line that is preceded by a comment.) Or, I could even make a complex statement, like this:

    int someNumber = 67;
    int someValue = 100;
    
    if (someNumber > someValue - 90)
    {
        // do something   
    }
  

Here, the computer will evaluate the expression "someValue - 90" before it does the comparison to "someNumber". After the comparison is done, the computer will decide if the entire expression is 'true' or 'false' and either execute the code inside the if block or not.

In addition to the if-else block, there is also a slightly more complex variation, which is explained below.

    int aNumber = 10;
    
    if (aNumber > 5)
    {
        // do something   
    }
    else if (aNumber == 10)
    {
        // do something else   
    }
    else
    {
        // do something else entirely   
    }
  

Here, you'll notice the additional else if block. You can have any number of else if blocks. The last else block is always optional, whether you have an corresponding else if block or not. Regardless of how many blocks you have in this type of control structure, only one of them is ever executed per sequence, even if a later block would be evaluated as 'true'. For example, examine the following:

  double myDouble = 505.9942;
  int value1 = 30;
  
  if (myDouble < 80)
  {
    // do something   
  }
  else if (value1 - 10 != 21)
  {
    // do something   
  }
  else if (value1 == 30)
  {
    // do something   
  }
  else
  {
    ...  
  }
  

You can see that the second if block will be evaluated as 'true'. The computer will then skip all the other blocks and continue executing code after the last else block. Even though block number 3 is also true, it is not evaluated because Java will always evaluate the expressions in the order they are listed and will stop after a 'true' condition is found. If you specifically want block 3 to be evaluated, you must separate it from the sequence of if-else blocks and wrap it in its own block. (See example below).

The last topic we'll visit for this lesson are called logical operators. They are helpful when dealing with control structures.

  char c = 'H';
  int number = 6;
  
  if (number == 6 && c == 'H')
  {
      // do something
  }
  
  if (!number == 9)
  {
      // do something
  }
  
  if (number == 0 || c == 'L')
  {
      // do something
  }  
  

The && operator is called the AND operator and is used when you want to test whether two or more conditions are true. So in this case, we are testing whether 'number' is equal to 6 AND 'c' is equal to the letter 'H'. The whole if statement is only evaluated as 'true' if BOTH conditions are met. In the second if block, you'll see the NOT operator working. The NOT operator will negate any expression. In this case, we are testing to see if 'number' is equal to 9. Clearly this statement is 'false'. However, the '!' before the expression negates it. The 'false' becomes 'true'. (If the expression had been evaluated as 'true', the '!' would have negated it to 'false'.) I could have just as well written if (number != 9), but I wanted to demonstrate the NOT operator. You'll find there are times when one or the other is more useful. The last if block demonstrates the OR operator, '||'. Here, we are testing if 'number' is equal to 0 OR c is equal to the letter 'L'. If either of these conditions are 'true', the entire if block is 'true' and its code is executed.

Note that I used a sequence of if blocks for this last bit of code. Unlike the previous example, these blocks are not tied together by else statements. Therefore, each one is evaluated regardless of the outcome of the previous blocks.

Hosted by www.Geocities.ws

1