Number crunching

A command line app (short for application) is a program that you run from a command prompt. All the interaction with a command line app is accomplished through the keyboard. The program that you created in the last lesson was a command line app, but it didn't do much. In this lesson, we'll create another command line app but this will perform some useful calculations. You'll notice that the prototype is not a command line app. It is a window app. We start with command line apps because they are the easiest to implement. We'll get to using windows in a later lesson.

Variables

A variable is just a name that you establish in your program to associate with a particular value (like the number 1 or the team name "Red Rebels"). Usually the value of a variable will change over the course of your program (hence its value is variable). Variables can be used to store various different kinds of data and so there are different types of variables. The most common variables are integers and Strings. We'll start by going over integer variables. To create a new integer variable, add the highlighted line below to your code from the last lesson.
public class Stakeout {
    public static void main (String args[]) {
        
int variableName;
System.out.println ("Hello World"); } }
This is called "declaring" a variable. Try to compile this code just like you did last lesson.
??? Make sure you got the semi-colon at the end of the variable declaration line
If you run the program you'll find that it does the exact same thing as it did before. We aren't doing anything with the variable yet, we're just declaring it.

In this case the variable is named "variableName". You can name your variable however you want as long as it follows these guidelines:
  • contains only letter, numbers, underscores (ie. "_"), and dollar signs (ie. "$")
  • doesn't begin with a number
  • doesn't contain any spaces
not a statement may indicate a bad variable name: check the guidelines for variable names and make sure your variables have valid names
';' expected may indicate a bad variable name: check the guidelines for variable names and make sure your variables have valid names
Usually you will name a variable depending on what it represents. For example, it might be important to know the number of units on the board. This is something that will change in the course of the game, so we decide to make a variable to keep track of it. We could use the name "numberofunits". Most people find this hard to read so instead use "number_of_units" or "numberOfUnits". Beginning typists tend to come up with short variable names using cryptic abbreviations. A beginning typist might call this variable "n". While "n" is a valid variable name, it will not be very easy to read your program, especially when the program gets bigger and you come back to reread your code and wonder what "n" really stands for. If you want a shorter name "numUnits" is probably about as short as you can get while still retaining the meaning. Get used to making descriptive variable names. You'll learn to type faster and it will make your life easier in the long run.

Once you have declared a variable you'll probably want to assign a value to it:
numUnits = 10;
This assigns the number 10 to the variableName variable. It doesn't have to be a plain number, it can also be the result of a computation:
numUnits = 10 + 5 - 3;
Hopefully the math is pretty self explanatory. We'll go over more about the mathematical rules later. Note that assignments to a variable must come after its declaration.

cannot find symbol This is usually indicative of a variable that is used without or before being declared.
Now you that you've assigned a value to your variable, you can use "numUnits" anywhere in your program in place of the value that you assigned it to.
public class ShowUnits {
    public static void main (String args[]) {
        int numUnits = 1;
        System.out.println ("The number of units is " + numUnits);
    }
}
Your program outputs "The number of units is numUnits" instead of "The number of units is 1" Make sure you didn't accidentally embedd the variable name in the string (the words in quotes). You have to add the variable to the string using the "+" operator, otherwise java thinks you just want to output the String "numUnits".
Variables have many purposes. Among other things, they make your code easier to read, eliminate redundant computation, and make maintenace easier. Let's expand our simple program so it can illustrate each of these points. Say that in our game the number of units doubles each turn. Each turn we will need to multiply the number of units by 2. Let's have our simple program print out how many units there will be after the first five turns. If we didn't have variables, this is what our program would have to look like:
public class DoubleUnitsWithoutVariables {
    public static void main (String args[]) {
        System.out.println ("The value is " + 1);
        System.out.println ("The value is " + 1 * 2);
        System.out.println ("The value is " + 1 * 2 * 2);
        System.out.println ("The value is " + 1 * 2 * 2 * 2);
        System.out.println ("The value is " + 1 * 2 * 2 * 2 * 2);
        System.out.println ("The value is " + 1 * 2 * 2 * 2 * 2 * 2);
    }
}
And this is what it looks like using a variable to keep track of the number of units:
public class DoubleUnitsWithVariables {
    public static void main (String args[]) {
        int numUnits = 1;
        System.out.println ("The value is " + numUnits);
        numUnits = numUnits * 2;
        System.out.println ("The value is " + numUnits);
        numUnits = numUnits * 2;
        System.out.println ("The value is " + numUnits);
        numUnits = numUnits * 2;
        System.out.println ("The value is " + numUnits);
        numUnits = numUnits * 2;
        System.out.println ("The value is " + numUnits);
        numUnits = numUnits * 2;
        System.out.println ("The value is " + numUnits);
    }
}
Easier to read: At first it might look that the code without variables is simpler. It certainly has less lines. But if we were to look at this program not knowing what it is, we would have now idea why we are doing these calculations. In the second program at least we can see that at each step we are multiplying the number of units by two and printing out the new value at each step. This makes a little more sense.

Eliminate redundant computation: In the first program we are doing a total of 15 multiplications. In the second program we are only doing 5 multiplications. The difference between 15 and 5 multiplications is not really significant (you'll notice that both programs run about the same amount of time), but in larger programs, this savings can add up.

Make maintenance easier: To add a few more steps to the first program, you'll have to copy the last line and then go back and add some more "* 2" to the end of the lines. To add more steps to the second program, all you have to do is copy the last two lines and then paste them to the end of the program as many times as you want. This is a very simple example of something called "code reuse". This will become a much bigger factor later in the game.

Follow-up exercise

Write a program that calculates the sum of the numbers from 1 to 10 and print out the current total at each step of the way. Use a variable to keep track of the current total.


Rate this lesson: *****