Page 1 of 1

Scope and Static Variables

#1 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,050
  • Joined: 15-July 08

Posted 27 February 2010 - 01:00 PM

Variable Scope
*Note: This is written with a Java-based focus, but is applicable in many other languages as well.


Introduction
Variable scope presents a serious problem to many of the newer programming students, particularly those new to object-oriented languages. In this tutorial, I will explain variable scope generically, as it applies to several languages, but all of my examples will be in Java.

Variable scope is simply the area of a program in which a variable exists and can be seen/used. There are many types of variables which I will cover simply here.

Global variables: known in Java as Class or Instance variables, and in C++ as global variables, these variables can be seen to many methods. Often, a change in one method will affect another indirectly through the use of globals.

Local variables: These can be a wide variety of different variables, but the key with locals is that it can only be used in the code block in which it was defined. If you attempt to use a variable defined inside one block in another, you will run into issues, as this cannot be done.

Global Variables
As I said before, global variables can be seen throughout the program or class. Often, globals are discouraged as often as possible, and it is said that the more local variables, the better. However, in some cases, they need to be used in order to share information between methods/functions. Here is an example:

class MyExample {
    // Define our global variable here
    private int globalVar;

    public void setVar(int num) {
        globalVar = num;
    }
   
    public void printVar() {
        System.out.println(globalVar);
    }

    public static void main(String[] args) {
        MyExample ex = new MyExample();
        ex.setVar(6);
        ex.printVar();
 
        ex.setNum(23);
        ex.printVar();
    }
}



In this Java example, you notice that globalVar can be set and accessed in any of the object's methods.

Local Variables
Another common type of variable scope is called local scope, which means that it is not accessible to anything except the block of code to which it belongs. That means that if you declare a variable within a set of brackets { }, then outside those brackets nothing else can see them and they only exist within that specific set of brackets. There is actually an exception to this rule, and those are called static variables and methods, which I will talk about later.

Local variables can be inside methods, try-catch blocks, loops, anything! Here is another example:
public class Main {

    public void printHighestNum(int[] intArray) {
        // Declare our local variable here. Notice that this variable
        // cannot be accessed in any other methods, but can be seen
        // EVERYWHERE WITHIN the method.
        int  highestNumber = intArray[0];

        // Notice that “i” can only be seen inside the loop and nowhere
        // else in this method, and it no longer exists at the end of the loop.
        for (int i = 1; i < intArray.length; i++) {
            if (intArray[i] > highestNumber) {
                highestNumber = intArray[i];
            }
         }

         System.out.println(highestNumber);
         // System.out.println(i);
        // See how that line causes an issue? That is because I no longer exists
        // No that the loop is done.
    }

    public static void main(String[] args) {
        int[] array = {1,4,2,6,7,4,3,76,91,23,-1};
        Main m = new Main();
        m.printHighestNum(array);
        
        // System.out.println(highestNum);
        // Notice how that line, too would not not work due 
        // to the fact the highestNum is local to pringHighestNum(),
        // and as such, cannot be seen anywhere else.
    }
}



Through that experiment, you see that local variables are truly local to their block.

Static Variables
So, are the “global variables” that I showed you really global? Actually, they were not, the just had visibility in their own class (their block). To make a variable truly global, the variable is both declared as public and static. A static variable, unlike the first example that I gave, is seen throughout the class. This means that if you have 4 different objects that access a static variable, then if one object makes a change to that variable, then all of the objects have the exact same change. Also, instead of being called through the object, like an object. They are accessed via a Class.

Object-Level access:
myObject.variable

Class-Level access:
MyClass.variable

Two good examples for static variables include an instance counter, which tells the number of objects have been created for that particular class and program-level constants.

public class Main {

    public static int count = 0;
    
    public Main() {
        count++;
    }

    public static void main(String[] args) {
        Main m = new Main();
        System.out.println("There are " + Main.count + " Main objects");
        
        Main n = new Main();
        Main o = new Main();
        System.out.println("There are " + Main.count + " Main objects");
    }
}



As you can see, the static variable is seen to all of the objects and can perform in this fashion. Finally, let me introduce the static constructor (Java specific). All that this does is gives the static values an initial value much like a constructor does. It is really only useful when these static variables are final as well, but here is the syntax:

public class Main {

    public static int count;

    // static constructor, let's set it to 2 just for kicks
    static {
        count = 2;
    }

    public Main() {
        count++;
    }

    public static void main(String[] args) {
        Main m = new Main();
        System.out.println("There are " + Main.count + " Main objects");

        Main n = new Main();
        Main o = new Main();
        System.out.println("There are " + Main.count + " Main objects");
    }
}



There you go! Now do you get scope? You'd better! :bigsmile:

Is This A Good Question/Topic? 1
  • +

Replies To: Scope and Static Variables

#2 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Posted 01 March 2010 - 12:09 AM

This is a great writeup about scope and variable resolution. Readers should take note that this is specifically in reference to lexical scope (or static scope) as the visibility of variables is determined by where they appear syntactically (or lexically).

A popular alternative to lexical scope is dynamic scope which makes variable visibility dependent upon the call stack and the order in which variables are declared.
Was This Post Helpful? 1
  • +
  • -

#3 singularity  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 17
  • View blog
  • Posts: 184
  • Joined: 17-October 08

Posted 15 March 2010 - 06:45 AM

This is really a wonderful topic to get a clear understanding of object Scope and creating objects in java.

Topic bookmarked!

Anyways!!

Quote

Often, globals are discouraged as often as possible, and it is said that the more local variables, the better.


Doesn't it contradict the OOPS concept, since there is no need to create objects if variables are local in scope.
Was This Post Helpful? 0
  • +
  • -

#4 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,050
  • Joined: 15-July 08

Posted 15 March 2010 - 07:11 AM

Well, since this tutorial is not OOP-centric, but meant to target any language. In Java, you can think of instance variables as being being variables local to that object...In Java, "global variables" could be public static editable variables.
Was This Post Helpful? 0
  • +
  • -

#5 sparkart  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 113
  • View blog
  • Posts: 690
  • Joined: 16-February 09

Posted 11 October 2010 - 08:52 AM

Quote

// Define our global variable here
private int globalVar;


Looks like a variable in the class's local scope.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1