Meaningless Drivel is fun!
The moose likes Java in General and the fly likes member vs. local Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "member vs. local" Watch "member vs. local" New topic

member vs. local

Cheryl Gray
Ranch Hand

Joined: Nov 17, 2000
Posts: 44
What is the difference between a variable being a member or being local?
This is what I understand:
class A
{ int aa; //here aa is a member
In what context would aa be local?

Anything is possible to those who believe.
Bear Bibeault
Author and ninkuma

Joined: Jan 10, 2002
Posts: 63865

A variable is considered 'local' when it is declared within the body of a method.
A member (or instance) variable is "in scope" for the entire duration of the object instance. Whereas a local variable will be in scope only from the point of declaration to the end of the block within which it is declared.
Be sure to ask for clarification if that doesn't clear things up for you.

[Asking smart questions] [About Bear] [Books by Bear]
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Maybe an example will help illustrate what has been explained:


Java API Documentation
The Java Tutorial
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
A member variable, aka instance variable, aka field is part of the object that is created on the heap. There is a place inside that object to track the current value of the reference that the variable holds. It stays there until the object itself is no longer referenced by anything, at which time it is rounded up by the gc.
A local variable, aka automatic variable is not part of the object. It is a variable that is created automatically when a method or block of code is executed that declares the variable, and lives on the stack that is associated with the method. When the method is over, the stack for that method is rudely cast aside and thus the local variable is destroyed.
You might enjoy reading Not all Variables are created Equal.

"JavaRanch, where the deer and the Certified play" - David O'Meara
I agree. Here's the link:
subject: member vs. local
It's not a secret anymore!