Recommended method for initializing a java object

advertisements

Are there any practical differences between these approaches? (memory, GC, performance, etc?)

while...{
   Object o=new Object();
   ...
   o=new Object();
   ...
}

and

Object o;
while...{
   o=new Object();
   ...
   o=new Object();
   ...
}


From Effective Java 2nd Edition:

The most powerful technique for minimizing the scope of a local variable is to declare it where it is first used. If a variable is declared before it is used, it’s just clutter—one more thing to distract the reader who is trying to figure out what the program does. By the time the variable is used, the reader might not remember the variable’s type or initial value.

Declaring a local variable prematurely can cause its scope not only to extend too early, but also to end too late. The scope of a local variable extends from the point where it is declared to the end of the enclosing block. If a variable is declared outside of the block in which it is used, it remains visible after the program exits that block. If a variable is used accidentally before or after its region of intended use, the consequences can be disastrous.

In other words, the difference in performance (CPU, memory) are irrelevant in your case. What is far more important is the semantics and correctness of the program, which is better in your first code example.