Understanding local variable initialization

I am reading J. Bloch's efficient Java, and now I am in the section on initializing local variables. Here is what he said:

Almost every local variable declaration should contain an initializer. If you do not yet have enough formations to initialize the variable reasonably, you should defer the declaration until you do so. The only exception to this rule applies to try-catch statements.

So what about instructions if-else? We need to initialize the variable only if some condition is met, and initialize it differently if it is not, for example

MyClass mc = null;
if(cond)
   mc = new MyClass();
else
   mc = new MyClass(1);
//use mc

Since it is not mentioned by J. Bloch, is it considered a bad programming method and should be avoided?

+4
source share
4 answers

In my opinion, the cleanest way should be:

final MyClass mc;
if (cond) {
   mc = new MyClass();
} else {
   mc = new MyClass(1);
}
//use mc

Since the last keyword will ensure that the variable will always be initialized only once (for a detailed explanation, look in your book at Point 15: Minimize Variability , page 73).

And this is what you cannot do in regular try-catch statements.

Moreover, it is more efficient and safer to always use curly braces .

+4
source

You had to initialize the variable no matter what before using it.

, , .

int a;
if (...) { a = 0; }
else { a = 1;} 

.

int a;
if (...) { a = 0; }

, , 'a' .

'?' , :

MyClass mc = cond ? new MyClass() : new MyClass(1);

'mc' , ( if/else), . , . , , .

+2
MyClass mc = null;

.. mc - if else. .

if else, , , .

+1

if-else, .

if-else, if-else.

.

+1

Source: https://habr.com/ru/post/1611885/


All Articles