Question: There seems to be two accepted variable declaration placements for Java variables, each with different *raison d'être*.

From the [Sun's code conventions](http://java.sun.com/docs/codeconv/html/CodeConventions.doc5.html) we can see:

> 
> Put declarations only at the beginning of blocks. (A block is any
>  code surrounded by curly braces "{" and "}".) Don't wait to declare
>  variables until their first use; it can confuse the unwary programmer
>  and hamper code portability within the scope.
> 
> 
> 

However in the highly praised ["Code Complete"](https://rads.stackoverflow.com/amzn/click/com/0735619670) and some other authors advocate for reducing the scope of a variable to a minimum. That is basically waiting to declare variables until their first use.

These two approaches are clearly contradictory although I can see the point for both of them.

Which should I follow? Is there any consensus on the matter?

Answer: 
> 
> That is basically waiting to declare variables until their first use.
> 
> 
> 

This is actually not true, and these two styes are not conflicting. Limiting the scope of the variable means that that variable, in fact, does not exist outside of that scope. E.g.

```
for(int i=0; i<10;i++){
   int a = 5;
   doSomething(a);
}

```

In this case, a is scope limited to the for block and this is what Code complete is referencing.

In any case I agree with sun, that variables within a scope (class, method, if block, etc.) should be declared at the beginning.
Those two statements do not need to be contradictory. Scope is decided by the curly brackets, so if you start a new set of brackets closer to where you use them, that is consistent with the Sun coding convention. Of course if you are just arbitrarily inserting scope limitations, that is a problem for reading the flow of the code.

However, I find it very important to declare fields at the top of the class, especially mutable fields. Understanding the state of an object can be the hardest part of a class over the long term, and putting the declarations at the beginning of the class clearly states what significant state the class holds.