Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects (Retired) Creating the MVP Prompting for Guesses

Martynas Kairys
Martynas Kairys
4,959 Points

what is the difference between variable and member variable?

I understand there are several types of variables in Java. Can anyone explain what are the differences?

amathiaitishar
amathiaitishar
13,229 Points

Simple! A local variable is the variable you declare in a function. A member variable is the variable you declare in a class definiton. 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 VanillaGodzila {
int a;
int b;
}

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

// Create an instance of VanillaGodzilla

VanillaGodzilla obj = new VanillaGodzilla();

// Assign new values to a & b

            obj.a = 1;
            obj.b = 65536;        

These variables belong to VanillaGodzilla, 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[]){

        VanillaGodzilla obj = new VanillaGodzilla();

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

I have struggled quite a lot before I had it crystal clear and hopefully this helps. Best,

1 Answer

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

A member variable is just part of the class. It is just like the other variables we have been creating, but it belongs to the instance of that class.

That make sense?