There's no "one size fits all" answer here because there are different reasons for declaring variables.
Static variables (declared directly within the class, with the static
modifier) are class-wide, rather than specific to a single instance. Usually static variables are final
- mutable global state is a tricky business.
Instance variables (declared directly within the class) are there to record the state of the object. They will be available within every instance method.
(Instance and static variables are both fields.)
Local variables (declared within a constructor or method) are only available within that method, and are effectively "temporary" data which is only required for that single method invocation. (If the method is called recursively, each call gets its own independent set of variables.)
So for each variable, consider whether it's logically part of the state of the object or not, and declare it in the appropriate place. Once you've decided what kind of variable it is, you can then determine the physical placement. For fields, it doesn't matter (much) exactly where you declare it - at the top of the file, in the middle, or at the bottom. The ordering between fields matters in terms of initialization, but it doesn't matter whether it's before or after a method that uses it. It's generally a good idea to declare all your fields in one consistent place though - personally I usually have:
class Foo
{
// Static variables
// Instance variables
// Constructors
// Methods
// Nested types
}
... but that's just a convention.
For local variables, it's generally a good idea to declare them as late as possible, within as small a scope as possible. So instead of:
int i;
int x;
for (i = 0; i < 10; i++) {
x = i * i;
System.out.println(x);
}
This would be preferrable:
for (int i = 0; i < 10; i++) {
int x = i * i;
System.out.println(x);
}
By limiting the scope of a variable, it's typically easier to reason about it.