Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

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
SOLUTION
Avatar of dpearson
dpearson

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

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.
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.
Avatar of gudii9

ASKER

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?
Avatar of dpearson
dpearson

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
Avatar of gudii9

ASKER

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
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.
They are using "property" to mean the same thing as a "member variable".
They are not methods, but something called a property.
data member and properties are basically synonyms
Avatar of gudii9

ASKER

Un my above comment quote it say 'list',what author meant by list there which contains four fields
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.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

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?
Avatar of gudii9

ASKER

what is the good book or link to become more knowledgeable in design and architectural areas. please advise
Effective Java is a very good place to start:
http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683

Doug
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
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
Avatar of gudii9

ASKER

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++
Avatar of gudii9

ASKER


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
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
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.
Avatar of gudii9

ASKER

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?
Avatar of gudii9

ASKER

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.
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/
Avatar of gudii9

ASKER

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
Were you looking for examples of using ParsePosition?
http://www.javased.com/?api=java.text.ParsePosition
Avatar of gudii9

ASKER

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
Avatar of gudii9

ASKER

as different topic i will open new thread for this