Is it necessary to have a default value of boolean in java?

497    Asked by JasonSharp in Java , Asked on Oct 6, 2022

For example, to store whether sound is on, I have a boolean originally named "isSoundOn":

private boolean isSoundOn=true;

However, the default value of boolean is false, but I want my application to turn on the sound at start. My question is, should I change the name of isSoundOn into isMute, so that it becomes "false" correctly by default?

Or in general, should I keep a boolean to be false by default, even if I may need to reconsider the name of boolean?

Answered by jay Trivedi

No, you absolutely should not choose variable names to conform to your language's default value of boolean in java.


The point of variable names is to make reading code easier for the maintainer. Default values are a detail of the language specification (or sometimes even of the implementation) and may or may not match with your intent in using a flag variable. Therefore it's much, much better to choose the variable name to be as clear as possible for the reader, and use explicit initialization if this is necessary to get the desired initial value.

(By the way, IMO there is no reason to use initialization if the well-defined default value does match your program semantics. Expressions like private boolean active = false; look uncomfortably as if the author didn't know about the language specification and make me wonder what else they don't know.)



Your Answer

Interviews

Parent Categories