Java Article 7 - Variable and Types

In this article we look at storing and using data in your program as it runs in the form of variables.

As your program runs it will need to receive, manipulate, and output data. The data is stored in memory and when your program ends the data is longer accessible. If you restart your program all your variables reset to their initial values, unless you intentionally load and save them somehow.

I won't go into it all here, but just know there are whole books written on memory types, stacks and heaps, and all the theory supporting modern memory management in computers. It gets very deep and very technical very quickly.

Variables are stored in data types. In Java and other languages like C++, C#, and Objective-C your Variables are broken up into different types representing the type of data the memory location holds.

Remember algebra in high school?

Remember X could be set to some number, like x=10. Then you would plug it into an equation, like z = x + 5? Well computers work the same way. 10 is your variable, X is the name of your variable which is also called an identifier.

The Java API documentation has an excellent summary of the primitive data types: oracle.com

Don't worry too much about all the differences for now, you will have to learn them later when you start using them. Two of the more common primitive types you will use are int (short for integer) and Boolean. Int is a positive or negative whole number with no decimals places (e.g. 10 not 10.1) and boolean is a variable that holds either a true or false value and is used for logical operations.

In addition to primitive data types there are variables stored in the form of objects. Examples of these more complex types are:

1. Strings: Strings hold one or more characters, or you could say a string of characters. 2. Arrays: a data type holding a collection of other variables 3. A reference: This is a name or pointer to a memory location. This is a more advanced topic so don't worry about it for now. 4. Objects: can even be referenced, evaluated, and stored as variables.

To use a type you have to declare it in your program. You do this by typing the type followed by the variable name, followed by the semicolon:

int myInt;
int weight;
boolean finished;
String myString;

We will get more into naming conventions later but you should try to pick a name for your variables that describes what value is being held. You should be able to look at the variable name in your program and remember what it does. This is part of making your program readable. In the workplace other people will have to read your programs so you want to make it as easy as possible for them to do so. It also helps you read your program as your program grows in length and complexity.

Also remember its convention to keep the first letter in variable names in lower case. This helps people identify them as variables. Your variable can also be multiple words linked together without spaces. The second and subsequent words are capitalized. This is again to help people read your code.

So if you int holds a weight value then call your int:

int weight;

If your program needs to keep track of how many skeletons and zombies there are in your game then you could use:

int numberOfSkeletons;
int numberOfZombies;

This method of capitalizing is called camel case since it resembles a camel with the capitalized "hump(s)" in the middle.

So in the examples above you are just declaring a variable. You are not setting it to a particular value. When you declare a variable by entering

int numberOfZombies;
you are telling your program to be ready to accept and work with a variable named numberOfZombies and that variable will take the form of an int. In programming terms you would say "it will be of type int."

Types are necessary because different types require different amounts of memory and your program has to prepare the memory allocation ahead of time. In addition to just declaring a variable you can declare and assign it. You assign it when you want to set the value ahead of time. So if you wanted the computer to know to put 10 zombies in the game to begin with, you could say:

int numberOfZombies = 10;

Keep in mind you can only declare a variable once, so later on if you wanted to reset the number of zombies you would just use:

numberOfZombies = 5;

Notice you leave out the type, since you already told your program the type. If you add the type the computer will think you are declaring it twice and it will show you an error message and refuse to compile. You can also do math on your variables in your methods. This is how calculations are typically performed in a program. So if your player killed a zombie you could have a method to deal with the zombie death and update the value of numberOfZombies:

public void zombieWasKilled()
{
	numberOfZombies = numberOfZombies - 1;
}

Expressions like the one above get evaluated right to left so the computer does the following:

Step 1) numberOfZombies = 10 therefore:

Step 2) numberOfZombies = 10 - 1;

Step 3) numberOfZombies = 9;

So you killed a zombie and you subtracted one. numberOfZombies now = 9;

Next time you call zombieWasKilled It would look like :

Step 1) numberOfZombies = 9 therefore:

Step 2) numberOfZombies = 9 - 1;

Step 3) numberOfZombies = 8;

We haven't talked much about method calls so don't worry if you don't understand it yet. Just be aware you do calculations with your variables. So below is a simple console application showing you a bit about the primitive data types, how to use them, and how they work in a program. Copy and paste and compile and run this and see how they work first hand.

public class Variables
{
 
//This is a comment
//Text in the same line that follows two slashes is a comment. Comments are not executed.
//Use comments to write notes, and explain what a section of code does.
 
     
    public static void main(String []  args)
    {
         
        String className = "Variables";
         
        //here we declare a variable zombieSaying, and set its value, "Grrrrr!".
        String zombieSaying = "Grrrrr!";
             
        //here we just declare an int, we will set its value later
        int numberOfZombies;
             
        //a boolean contains either a true or false value.
        boolean isZombieAwake = true;
         
        System.out.println(className);
        System.out.println("____________");
         
        //here we assign a value to numberOfZombies
        numberOfZombies = 10;
         
        System.out.println("numberOfZombies = "  + numberOfZombies);
         
        System.out.println("The zombie says: "  + zombieSaying);
         
        //Here we do a bit of math. This add 5 to the total number of zombies
        numberOfZombies = numberOfZombies + 5;
        System.out.println("numberOfZombies (after adding 5)= "  + numberOfZombies);
        System.out.println("Is the zombie awake? (true or false): "   + isZombieAwake);
    }
}

Also know that like methods and classes, variables have scope. A variable's scope (its visibility) can be declared:

private int numberOfDeadZombies;

A variable's scope also comes from in part from where you declare it in your program: for instance a variable declared in a method is only visible and useable within that method. These are called method variables. Naturally you have to decalre and assign your variables before you try to use them, so variable declaration and assigment is often perfoemed at the beggining of the class or method. We will talk more about scope later.

I remember in the 1990's it taking some time to really understand scope when I was going from progamming lanuguages like Basic and Fortran to the more complex C++ where scope based on location really becomes important.

Now that we have covered a couple of console methods examples we are going to jump into windowed methods so you can write some programs that actually run in a window and look like the programs you are accustomed to.