I'm confused about variables and their scope. What's the difference between a member variable, and a local variable?


Simple! A member variable is a variable that belongs to an object, whereas a local variable belongs to the current scope. Hmm... Still confused?

When we define a class, we can give that class member variables. These variables are members of that class. Take, for example, the following class declaration.

public class MyClass {
int a;
int b;

MyClass has two member variables, a & b. When we define an object instance of MyClass it will still have two member variables, a & b. We can reference these members using the '.' character.

// Create an instance of MyClass
MyClass obj = new MyClass();

// Assign new values to a & b
obj.a = 1;
obj.b = 65536;

These variables belong to MyClass, and are known as member variables. On the other hand, if we declare variables inside of a function, we call these local variables. These variables are local to a particular function, and not publicly accessible. For example, in the following function, we have no way of accessing the obj variable outside of the main(String[]) function.

public static void main (String args[])
        MyClass obj = new MyClass();

        System.out.println ("A" + obj.a);