Skip to content

Variables#

One very central concept in programming are Variables. You will need them all the time.

Variables store things about your program. This can be important numbers like how many points a player currently has or how much damage their sword does. But eventually you will learn how to store any kind of digital information in variables.

A drawer labeled "Score"

Mark all your drawers!
Photo: Jan Antonin Kolar, 2018

A very apt mental model is a drawer that you can put stuff into. That drawer has a neat little label telling you (and others!) what is supposed to be in there. We call this the name of the variable. You can open the drawer and look at what's inside and you can change it at any time. We call the thing that is contained in your drawer the value of a variable. The nice part is, that you can now use the name in your program, regardless of what value is stored in it.

Declaring a Variable#

To use a variable in your program, it must be declared once – you must formally state that you want to have a variable of a certain name, and that it will be used to store a certain kind of content. In this next example, we want to store an integer number (int) under the name score.

int score;

int is also what we call a Type, and we will get into types a little later.

Importance of good names#

Giving your variable a good, readable, understandable, distinguishable name is the key to understanding your programs. The best programmers I know have a thesaurus on their desks. Sometimes, there really is a difference between points and score. A good variable name conveys intention. Your player may have a destination or a target. Both could be locations, but one of them sounds like a ride on the bus and the other sounds like combat. Your calendar might have variables for when an event starts and maybe information about who invited you. Both could be called from, but a better name would be startTimestamp for one and organizer for the other.

There are some hard rules which are imposed by your programming language. A variable name cannot start with a number, that's why 2player will not work. You can also not choose a name that is a keyword in Java, so interface is out of the question, too. A variable name must not contain spaces, so you can't call a variable player name.

On top of that, there are some softer rules that have emerged between developers. While you technically could use Score1 as variable name, you should not. In Java, most developers use lower case variable names with something we call "camelCase" - whenever multiple words make up a variable name, we write the beginning of the next word in a capital letter. This makes incomePerCapita more readable than incomepercapita. Also there's a convention around ALL_CAPS names. These are commonly reserved for things that stay constant. All of these conventions are not enforced by the programming language, but they help other programmers understand your intentions.

Rules vary

Different programming languages may have different rules and conventions. Also employers may impose their own "coding style"2 onto their employees. When in doubt, look at existing code and try to match the style. Consistency is more important than your personal preference.

Keystrokes are free. Use them.

Some programmers cultivate the habit of single letter variable names. For the purpose of this course, please avoid single letter variables. There are exceptions to this rule when single letter variables are OK: Coordinates may be called x, y or z - in this case, that's really all you need. Also the counter of a loop may be called i or j because this really is the most common name for these and everyone should recognize these easily.

Initializing a Variable#

This is a fancy term for "let's give our variable its first value". Oftentimes, we do declaration and initialization in one step like this:

  int score = 0;
//int score        -> Declaration
//    score = 0    -> Initialization

Error in Processing when you try accessing an uninitialized variable

When our game starts, you will not have gained any points, yet. Our score shall start at zero. If we didn't give it any value, we would be presented with an error, because your computer does not like to guess what you meant. Unless you have a good reason, you should initialize all variables directly when you declare them.


Reading a Value from a Variable#

This is where the fun begins: if we have a variable that contains some kind of number, we can use that in any place where we would otherwise put a number directly!

int score = 25;
println(score); // will print 25 to the output window

Changing the Value#

Printing the variable before and after a change

The value of a variable can be changed at any time, and it will store the new value:

int score = 0;
println(score); // prints 0
score = 25;
println(score); // prints 25

If you've paid attention in math, you might have flinched just now. Because in math this is not how we use the equal sign (=). In math something would have been wrong. score couldn't be equal to zero in one place and then equal to 25 just a little later. In programming, though, the = sign means "please assign whatever stands on the right side to the variable on the left side" — it is an assignment operator. Unlike math, score does not have one fixed value across a whole math problem. It is a container in our programs to store whatever we need to store at the time. Some programming languages actually use something else as the assignment operator to make this extra-obvious.

But why do we use variables?#

Variables server many purposes, but the two most important things are:

  • We store things that change over time or that we get from somewhere else (so we can't really know the value at the time we write the program).
  • We give part of our code meaningful names to make our programs easier to read.

Let's consider this example:

println(999.99 * 1.19); // WHAT ARE THESE NUMBERS?!

And compare it to this second example:

float netPrice = 999.99;
float taxRate = 1.19;
println(netPrice * taxRate); // ah, this makes some kind of sense.

While the second example is longer, it is also much easier to understand. Variable names can help you figure out what is being calculated and why. Sometimes we declare variables just to get rid of "magic numbers" and instead put a meaningful name on them.

Relevant excerpt from Learning Processing#

(the section starts at 1:29:31 and runs through 1:43:05, the video should start and stop on these automatically.)


  1. Interestingly, in C#, Variables and Function names are commonly written with a capital first letter. 

  2. Here are two examples: Google's Style Guide for Java or Apache's Coding Standards for Java