Monday, May 21, 2012

Variable Scope: Life's too short




Nothing lasts forever, all good things must come to an end, sometimes what you leave behind is truly gone, can't take it with you after death, etc.

Programming is no different. Nothing is around forever. Unlike life, however, you always know when something is going to leave or be destroyed. You know because of the idea of variable scope! Scope is how long a variable exists and where it can be seen from.

Kids understand the idea of scope very well. When they have friends over, they know that they have some toys they are going to let everyone play with, some toys they are going to show to their closest friends when most people leave, and some toys they are going to keep completely to themselves. They also know that eventually a toy will get destroyed and they can't play with it any more at all.

Let's look at the simplest example of scope:

We have a variable myString that we created inside of main. When main finishes, the program is done and exits. When this happens, myString is destroyed and no longer exists (When this happens, we say it has "passed out of scope"). This is the equivalent of a kid playing with a toy until they are done with it, and then deciding to throw it into the trash.

Not that interesting write? But what if we have more than one kid playing (I.E. what if we have more than one function?)


Now we have two variables: name and myString. One of the keys to understanding scope is to look at code blocks. In java, code blocks are lines of code contained within curly braces ({ }). In our example, both of our functions are contained within {} so they are in their own code blocks. myString cannot be used inside of printName() and name cannot be used inside of main. If we tried something like


We would get a compiler error because printName() doesn't have a myString. Here's something to watch out for though.


What do you think will happen when main hits the println? It will still print out "Hello, World". Why?

When the function printName is called, we enter a new function and no old variables exist from that perspective. When we declare String myString inside of printName we are creating a new variable that just happens to have the same name as another variable we used, but stores something completely different and doesn't effect the first variable.

What if we try the reverse:


The println(name) from main will print "Guy" and the println(name) in printName will print "Computery". Because printName() creates a new name variable, which is destroyed when the method exits leaving the name that contains guy to be printed.

Trippy eh? Good stuff.

No comments:

Post a Comment