views:

172

answers:

6

While studying java with several books, none of them seem to make it clear when to use which term. Right now I understand it as follows:

Variables are defined within a method, while fields are part of a class.

+1  A: 

You are correct. Variables can be be local to a method. Fields are variables that belong to the class.

EDIT : Fields can be private, protected, or public.

fastcodejava
+8  A: 

Edit:

You have the right idea.

After going back to the Java Documentation, I'll use their terminology:

  • Member variables in a class—these are called fields.
  • Variables in a method or block of code—these are called local variables.
  • Variables in method declarations—these are called parameters.

Variables refer to fields, local variables, and parameters.

Reed Copsey
+1  A: 

Yes, that's correct. Fields are also called members.

tangens
+4  A: 

"Variables" is a more general term than "fields". But your summation is basically correct. A field is a class-level variable.

froadie
A: 

I think you are right to stress the difference. A variable is something that can change, a field is rather a member that has a value, this value can be final in which case calling it a variable seems a bit strange.

Hubert
Any variable, including a local variable, can be final.
MatrixFrog
Interestingly in Scala, we don't have the final keyword, instead we declare variable with `var` and final value with `val`.
Hubert
A: 

In java, a variable is anything which can change its value over the period of execution, while a field (which can also be called a "member" variable of a class) belongs to a class.

A constant/final can be though of (although some may disagree) as opposite of variable.

A Field belongs to a class and can be a variable or constant/final.

Elister