difference between member and local variables.

Hi,

I would like to know  difference between member and local variables. when to use which one. What are the other names that are commonly used for them.
please advise
LVL 7
gudii9Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

dpearsonCommented:
Member variables belong to a class, so they last as long as the object (of that class type) does.
Local variables are just short lived variables within a function (or method).

You should basically use local variables whenever possible.  You don't want things to hang around when you no longer need them.  So if you only need them in a particular method, declare them as local variables and they'll go away as soon as the method ends.

I'm not sure what you're asking for about the other names that are used for them.

Doug
0
zc2Commented:
Just wanted to add to the perfect  dpearson's explanation, that local variable could be local to a block it declared within, not the whole method.
0
gudii9Author Commented:
Member variables belong to a class, so they last as long as the object (of that class type) does.
Local variables are just short lived variables within a function (or method).

how do i decide particular variable(say testVariable) that i am thinking to write on particular class (say TestClass) should go as local variable or as member variable?

I guess these concepts dealt in java design, architecture related books, courses? Can you please advise any good sites, resources on this.
0
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

zc2Commented:
It simple. Think, would the value of the variable be used in the future code executing. If it will be needed later, make the variable a data member. If you know for sure that you won't need the current value any after the method has completed, make the variable local local.
0
gudii9Author Commented:
If you know for sure that you won't need the current value any after the method has completed, make the variable local local.
there could be scenarios where the called local variable(in class A) is a member variable in other class (classB)right

ClassA{
A a=new A();
}

ClassB{
testMethod(A a){

}
}


Similar to below link

http://www.homeandlearn.co.uk/java/java_method_parameters.html

http://www.homeandlearn.co.uk/java/field_variables.html

int total( int aNumber ) {
int a_Value = aNumber + 20;

return a_Value;
}

int total( int aNumber ) {
int a_Value = aNumber + 50;

return a_Value;
}

Open in new window


aNumber  needs to be local or member variable?
0
dpearsonCommented:
ClassA{
A a=new A();     // "a" is a member variable
}

ClassB{
testMethod(A a){  // "a" is a local variable here
}
}

Open in new window


In here:
int total( int aNumber ) {
int a_Value = aNumber + 20;

return a_Value;
}

int total( int aNumber ) {
int a_Value = aNumber + 50;

return a_Value;
}

Open in new window


aNumber  is a local variable.  So is a_Value.  Anything defined in a method (i.e. where it has the 'type' next to it like "int a") is always a local variable for that method.

You only get member variables when you declare them inside the class - outside of any methods.

And you should always try to use local variables when possible.

Doug
0
gudii9Author Commented:
The four fields that we set up are on the list. They are not methods, but something called a property.

what they meant by list in below link
http://www.homeandlearn.co.uk/java/field_variables.html
0
zc2Commented:
there could be scenarios where the called local variable(in class A) is a member variable in other class (classB)right
A variable can not be in two places simultaneously. You probably meant having two or more references to an object in different places?

In the second sample, aNumber  could be method parameter or data member. That solely depends on the task you are implementing.

Be also aware that it's not recommended that a method has a side effect. In other words, if aNumber  is class' data member, the method should not modify it if the method's purpose is just do some calculations.
0
dpearsonCommented:
They are using "property" to mean the same thing as a "member variable".
0
zc2Commented:
They are not methods, but something called a property.
data member and properties are basically synonyms
0
gudii9Author Commented:
Un my above comment quote it say 'list',what author meant by list there which contains four fields
0
zc2Commented:
The mentioned list is the dropdown hint window the development environment shows when you type the reference variable name and then type the dot character.
This is just a feature of the IDE software not the Java language itself.
0
Jim CakalicSenior Developer/ArchitectCommented:
A "member variable" is what I would refer to as a "field". A "variable" would be an "auto local" where auto(matic) refers to the allocation/deallocation of space for the variable as program flow enters or leaves the scope and local refers to the visible scope of the variable.

Auto local variables are scoped to the block in which they are declared. If that block is small (say an if statement) then the space for the variable is allocated on the stack as the program enters the body of the if block and deallocated when the if block is exited. The compiler knows that the variable will only exist during this narrow window and so only permits source code references to it within the enclosing block or scope of (in this example) the if statement body.

In contrast, fields have a much broader scope and lifespan. Instance fields are allocated when an object is instantiated, live for as long as the object lives and are visible to all code within the class and potentially subclasses, A static field has class scope and a lifespan that equals the lifespan of the class (from when it is loaded by the classloader to when it is unloaded) which may be the entire run of the application.

Another significant difference is initialization. Fields (both instance and class) are guaranteed to be initialized to a default value (zero or null) when the object is instantiated (instance field) or the class is loaded (static or class field). Auto locals receive no such treatment and will contain "garbage" from the stack so the compiler (we're talking Java here) will issue an error if your code attempts to reference an auto local if it has not been initialized.

Deciding between a field and an auto local is usually a fairly obvious design decision. Fields constitute part of the knowledge that an object has. In the case of an entity class (something like Person, Company, Vehicle, Order, etc.) that is part of you domain these are commonly referred to as properties. A Person might have firstName, lastName and birthDate properties that make up the facts or information the Person object knows. Each Person object has a discrete set of such facts specific to the instance. In the case of other object categories (e.g., service objects like UI controllers or DB repositories) fields would contain non-client references that the object needs to collaborate with or delegate to. Auto local variables are typically temporary variables that are used as part of a calculation or to hold intermediate results. There's no value to their surviving the algorithm in which they appear. If there is then there's a good chance that they should be exposed as part of the return value of the method in which they appear.

A potential overlap case deals with knowledge that can be derived. For example, returning to our Person object, ageInYears could potentially be represented as a field but may more conveniently be calculated and live, for the duration of the calculation, as an auto local. Calculation of age from birthDate is fairly simple and quick. Keeping the age as a field would necessitate synchronizing it with changes (potentially) to birthDate and might violate design conventions which typically expose simple properties using getters and setters. The methods getBirthDate, setBirthDate and calculateAgeInYears constitute a fairly consistent and comprehensible API with the method name including "calculate" to indicate that a potentially nontrivial algorithm was at work. The method could even possibly take a reference date and calculate the age of the individual on the reference date given their birhtDate. If, instead of calculateAgeInYears, we were to add getAge and setAge the developer would assume simple property access/modification. But then, what would be the semantics of combining setAge and getBirthDate? This would be confusing or require a number of assumptions. I will typically start by assuming anything that can be calculated, counted or otherwise derived is done so with some kind of query method that performs the computation using auto local variables to hold intermediate results. That decision could be affected by the cost of computation and the desire to cache the value once computed (e.g., the java.lang.String class used to recalculate the hashCode every time it was called despite String objects being immutable; this was changed later to lazily compute hashcode when first requested and cache the value to serve later requests - the tradeoff was the memory for every String vs the performance advantage of computing the value only once). So fields (IMO) are part of the non-derivable knowledge held by an instance. Everything else is auto locals or method parameters.

Regards,
Jim
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
gudii9Author Commented:
In the case of other object categories (e.g., service objects like UI controllers or DB repositories) fields would contain non-client references that the object needs to collaborate with or delegate to. Auto local variables are typically temporary variables that are used as part of a calculation or to hold intermediate results. There's no value to their surviving the algorithm in which they appear. If there is then there's a good chance that they should be exposed as part of the return value of the method in which they appear.

i was not clear on above. What it means by non-client references. How to expose as return value. can you please provide simple code example or link explaining this concept?
0
gudii9Author Commented:
what is the good book or link to become more knowledgeable in design and architectural areas. please advise
0
dpearsonCommented:
Effective Java is a very good place to start:
http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683

Doug
0
Jim CakalicSenior Developer/ArchitectCommented:
By "non-client reference" I meant primarily other objects with which this object collaborates. Say you have a controller object that handles a funds transfer request accepting as inputs the source and destination account numbers and the amount to transfer. In a simple design, this TransferController would need a reference to a Repository object which it could use to get Account details using the provided account numbers as below.

public class TransferController {
    private AccountRepository accounts;

    public TransferController(AccountRepository accounts) {
        this.accounts = accounts;
    }

    public void transfer(String from, String to, BigDecimal amount) throws BankingException {
        Account fromAccount = accounts.getById(from);
        Account toAccount = accounts.getById(to);

        fromAccount.debit(amount);
        toAccount.credit(amount);
    }

Open in new window


The AccountRepository would be a field on the TransferController but not something that was visible to a client of the class -- there would be no public getAccountRepository method because it isn't (or shouldn't be) important to the clients of (other code that uses) TransferController. The fromAccount and toAccount are auto local variables. TransferController uses them in the course of handling a transfer but has no need to retain references to them beyond that scope.

An example of a method that returns internal temporary variables is SimpleDateFormat.parse. It takes ParsePosition object pos and "attempts to parse text starting at the index given by pos. If parsing succeeds, then the index of pos is updated to the index after the last character used (parsing does not necessarily use all characters up to the end of the string), and the parsed date is returned. The updated pos can be used to indicate the starting point for the next call to this method. If an error occurs, then the index of pos is not changed, the error index of pos is set to the index of the character where the error occurred, and null is returned."

Now one could argue that the index of the last character used and even perhaps the errorIndex are internal details of the parsing algorithm. In over 15 years of developing with Java I don't recall ever needing to use them. Instead of being fields in the SimpleDateFormat object itself that you would need to query and preserve after each call to parse, the values, which probably started as temporary auto local variables in the method, are returned in the ParsePosition object.

In some cases internal information is "returned" as fields of an Exception that is thrown (see PatternSyntaxException.

Jim
0
Jim CakalicSenior Developer/ArchitectCommented:
As far as books, you might consider Object-Oriented Design and Patterns by Cay Horstmann. I also like Object-Oriented Design Heuristics by Arthur Riel, though the examples are in C++.

Regards,
Jim
0
gudii9Author Commented:
Effective Java is a very good place to start:
http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683

i have this book and read once. I think i should read few more time to sink those concepts to my mind
As far as books, you might consider Object-Oriented Design and Patterns by Cay Horstmann.

i will buy this as well as i am not familiar with c++
0
gudii9Author Commented:

Effective Java is a very good place to start:
http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683
i have this book and read once. I think i should read few more time to sink those concepts to my mind
what is effective way of reading technical coding books so as to remember concepts forever. please advise
0
Jim CakalicSenior Developer/ArchitectCommented:
Eat lots of fish? ;)

Seriously, though ... something that helps me retain material is if I can write code, even a unit test, that demonstrates the concept. The act of typing the code completes a circuit for me that ingrains the concept more deeply.

Jim
0
dpearsonCommented:
what is effective way of reading technical coding books so as to remember concepts forever. please advise

Personally I joined a local group of engineers and we get together and "read a book" together (we read a chapter or two every week and then get together to discuss the concepts).  It's a huge help.  If you search around for local Java user groups you'll likely find similarly interested people - it's a great way to learn and get more opinions and ideas on how to write software.
0
gudii9Author Commented:
I joined a local group of engineers and we get together and "read a book" together

it is interesting. Are there any of these groups near atlanta area?
0
gudii9Author Commented:
An example of a method that returns internal temporary variables is SimpleDateFormat.parse. It takes ParsePosition object pos and "attempts to parse text starting at the index given by pos. If parsing succeeds, then the index of pos is updated to the index after the last character used (parsing does not necessarily use all characters up to the end of the string), and the parsed date is returned. The updated pos can be used to indicate the starting point for the next call to this method. If an error occurs, then the index of pos is not changed, the error index of pos is set to the index of the character where the error occurred, and null is returned."
any good example on this. I could not find one where index pos is updated.

Please advise.
0
dpearsonCommented:
Are there any of these groups near atlanta area?

Go attend one of the meetings of the Atlanta Java User's group and they'll be able to tell you more about what's going on in your area:
http://www.ajug.org/
0
gudii9Author Commented:
An example of a method that returns internal temporary variables is SimpleDateFormat.parse. It takes ParsePosition object pos and "attempts to parse text starting at the index given by pos. If parsing succeeds, then the index of pos is updated to the index after the last character used (parsing does not necessarily use all characters up to the end of the string), and the parsed date is returned.

any good example, link on this concept? please advise
0
Jim CakalicSenior Developer/ArchitectCommented:
Were you looking for examples of using ParsePosition?
http://www.javased.com/?api=java.text.ParsePosition
0
gudii9Author Commented:
when i ran i got

import java.text.NumberFormat;
import java.text.ParseException;
import java.text.ParsePosition;


public class Parsing {
	public static void main(String[] av) throws ParseException {
		  String input="11 ss";
		  ParsePosition pp=new ParsePosition(0);
		  NumberFormat.getInstance().parse(input,pp);
		  if (pp.getIndex() != (input.length() - 1))   throw new RuntimeException("failed to parse");
		}
}

Open in new window


Exception in thread "main" java.lang.RuntimeException: failed to parse
      at Parsing.main(Parsing.java:11)
please advise
0
gudii9Author Commented:
as different topic i will open new thread for this
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Java

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.