Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is it a bad practise to not initialize primitive fields in a class?

Java primitives always have a default value in the memory of O (booleans are false = 0). So why is it considered as a bad practise to not initialize them, if they even have a predefined value because of this mechanic? And in arrays, even with initialization of a new int[8], all the values in it arent really initialized, but that isnt frowned upon...

like image 933
Pwnie2012 Avatar asked Jan 06 '14 12:01

Pwnie2012


People also ask

What happens when you don't initialize the fields and constructor of a Java class?

A constructor is typically used to initialize instance variables representing the main properties of the created object. If we don't supply a constructor explicitly, the compiler will create a default constructor which has no arguments and just allocates memory for the object.

What happens if you don't initialize an instance variable of any of the primitive types in Java?

The instance variable is declared inside a class but not within any method, constructor, block etc. If we don't initialize an instance variable, then JVM automatically provide default value according to the data type of that instance variable.

What happens if you don't initialize a variable Java?

If you declare a variable as final, it is mandatory to initialize it before the end of the constructor. If you don't you will get a compilation error.

Is it necessary to initialize variables in Java?

Java designers believe every variable should be properly initialized. To initialize a variable is to give it a correct initial value. It's so important to do this that Java either initializes a variable for you, or it indicates an error has occurred, telling you to initialize a variable.


1 Answers

By explicitly defining a value, it's clear that you intended that value at that point of execution. If not, another reader might interpret it as if you either forgot to initialize this variable or you don't care at that point (and will set it somewhere else later).

In other words, it's some kind of implicit documentation. Generally, it's considered better practice to write verbose code for better readability; i.e. never use abbreviations for methods names, write them out!

Also, if you have to write line comments (//), you can almost always replace them by wrapping the following code into a well-named method. Implicit documentation ftw! :)

like image 62
Cedric Reichenbach Avatar answered Nov 15 '22 10:11

Cedric Reichenbach