This question already has answers here:
Default value of 'boolean' and 'Boolean' in Java
(8 answers)
Closed 8 years ago.
I just want to know if there is a difference in Java between:
private boolean someValue;
private boolean someValue = false;
The second line maybe is just a time wasting?
EDIT (SUMMARY):
From the answers I found that there is almost no difference, but:
"Relying on such default values, however, is generally considered bad programming style."
But there are some strong arguments not to do so - see accepted answer below.
EDIT 2
I found that in some cases boolean value must be initialized, otherwise the code will not compile:
boolean someValue;
if (someValue) { // Error here
// Do something
}
In my NetBeans IDE I got the error - "variable someValue might not have been initialized".
It's getting interesting.. :)
All instance and class variables in Java are initialised with a default value:
For type boolean, the default value is false.
So your two statements are functionally equivalent in a single-threaded application.
Note however that boolean b = false; will lead to two write operations: b will first be assigned its default value false then it will be assigned its initial value (which happens to be false as well). This may have an importance in a multi-threaded context. See this example of how explicitly setting the default value can introduce a data race.
Relying on such default values, however, is generally considered bad programming style.
I would argue the opposite: explicitly setting default values is bad practice:
it introduces unnecessary clutter
it may introduce subtle concurrency issues
If you didn't initialize it, it will be false. So there is no difference between them.
The default value of boolean data type is false so we can say that there is no difference.
There is no difference, from:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
It's not always necessary to assign a value when a field is declared.
Fields that are declared but not initialized will be set to a
reasonable default by the compiler. Generally speaking, this default
will be zero or null, depending on the data type. Relying on such
default values, however, is generally considered bad programming
style.
If you declare as a primitive i.e. boolean. The value will be false by default if it's an instance variable (or class variable).
If it's an instance variable Boolean it will be null.
If it's declared within a method you will have to initialize it, or there will be a compiler error.
Related
This question already has answers here:
What is the difference between Boolean.TRUE and true in Java?
(7 answers)
Closed 9 days ago.
I had written a code of which a rough snippet is as follows:
boolean isCalledFromAction = Optional.ofNullable(requestParams.get(IS_CALLED_FROM_ACTION))
.map(val -> true)
.orElse(false);
My team lead said to always use existing classes and insisted to use Boolean class like below:
boolean isCalledFromAction = Optional.ofNullable(requestParams.get(IS_CALLED_FROM_ACTION))
.map(val -> Boolean.TRUE)
.orElse(Boolean.FALSE);
My question is I see Boolean.TRUE will make unnecessary a Boolean type object. When to use true and when to use Boolean.TRUE? Why in first place, Boolean.java class contains a wrapper object for true and false? I mean, they have auto-boxing so they can directly do like Boolean x = true; instead of Boolean x = Boolean.TRUE.
I have read answers on existing questions on SO related to performance but here I am interested in their usage scenarios.
At first something general
The main difference between boolean and Boolean is that a Boolean can be null, while a boolean cannot. So when you have a check if(a) {...}, with a being a Boolean, this might lead to a nullpointer exception. In this case, you would prefer to have if(Boolean.TRUE.equals(a)) {...}, because the equals method of Boolean would return false in case a is null.
Your specific case
What you suggested there is equivalent to
isCalledFromAction = Optional.ofNullable(requestParams.get(IS_CALLED_FROM_ACTION)).isPresent();
Not that isPresent actually returns a boolean and not a Boolean, as do most of the JDK internal methods that I've come across. Apart of that, I would say using true or false vs. Boolean.TRUE or Boolean.FALSE shouldn't make a real difference in most of the cases and might even be considered a matter of taste. In a large project, though, you would want to use one or the other consistently to not end up with a mess.
Constant, just one immutable object
You asked:
My question is I see Boolean.TRUE will make unnecessary a Boolean type object.
No, multiple objects are not created.
As commented by Culloca, Boolean.TRUE is a constant, referring to a singe object instantiated once when the class loads. As an immutable object, there is no need to have more than one.
Let’s look at the implementation found in the open source code at the OpenJDK project.
public static final Boolean FALSE = new Boolean(false);
The static means an instance is created when the class loads. The final means the reference named FALSE will never be re-assigned to another object. So one, and only one, object.
Avoid excessive auto-boxing
You are right to be concerned about unnecessary auto-boxing. Boxing is not magic; it takes CPU cycles to execute.
Going out of your way to use Boolean.FALSE where you know the primitive false is needed is pointless and a bit silly.
Such a practice is often harmless. If the code is infrequently executed, then you’ll see no significant impact on performance. And in some situations I would guess that the compiler might optimize away the boxing, though that is just a guess on my part.
FYI… Work is underway by the Java team to blur the sharp distinction between primitives and objects created by Java’s two parallel type systems. So the nature and impact of boxing may change in future versions of Java.
No need for Optional
Your code is overly elaborate.
You commented:
The type returned by requestParams.get(IS_CALLED_FROM_ACTION) is a string. If it is not null, I want to set isCalledFromAction to true.
Change this:
boolean isCalledFromAction = Optional.ofNullable(requestParams.get(IS_CALLED_FROM_ACTION))
.map(val -> true)
.orElse(false);
… to use Objects.nonNull:
boolean isCalledFromAction =
Objects
.nonNull (
requestParams.get( IS_CALLED_FROM_ACTION )
) ;
Why must local variables, including primitives, always be initialized in Java? Why is the same not applicable in the case of instance variables?
Basically, requiring a variable to be assigned a value before you read it is a Good Thing. It means you won't accidentally read something you didn't intend to. Yes, variables could have default values - but isn't it better for the compiler to be able to catch your bug instead, if it can prove that you're trying to read something which might not have been assigned yet? If you want to give a local variable a default value, you can always assign that explicitly.
Now that's fine for local variables - but for instance and static variables, the compiler has no way of knowing the order in which methods will be called. Will a property "setter" be called before the "getter"? It has no way of knowing, so it has no way of alerting you to the danger. That's why default values are used for instance/static variables - at least then you'll get a known value (0, false, null etc) instead of just "whatever happened to be in memory at the time." (It also removes the potential security issue of reading sensitive data which hadn't been explicitly wiped.)
There was a question about this very recently for C#... - read the answers there as well, as it's basically the same thing. You might also find Eric Lippert's recent blog post interesting; it's at least around the same area, even though it has a somewhat different thrust.
In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables don't have a default value. Unless a local variable has been assigned a value, the compiler will refuse to compile the code that reads it. IMHO, this leads to the conclusion, that initializing a local variable with some default value (like null, which might lead to a NullPointerException later) when it is declared is actually a bad thing. Consider the following example:
Object o;
if (<some boolean condition>)
o = <some value>;
else
o = <some other value>;
System.out.println(o);
An initialization of o with null is completely unnecessary, since the Java compiler checks at compile time, that any code-path initializes o (with either null or some non-null value) before the variable is read. That means, that the compiler will refuse to compile the line System.out.println(o); if you would comment out any of the two initializations of the variable o in the code snippet above.
This holds for Java, and maybe for Java only. I don't know about language like C#. In good old C (and maybe C++) however, it is still recommended to always initialize variables when declaring them, AFAIK. Such "old-school" programming languages might be the reason, that the recommendation to always initialize variables pops up in books and discussions about modern languages like Java, where the compiler keeps track of whether a variable has been initialized or not.
Not totally true. Local variables only need to be initialized if being reference. A local variable can be left uninitialized if never referenced. For example:
int x; // Valid
int y;
println("y=" + y); // Not valid since y's value has never been assigned
Well, in case of local variable it's clear what it means 'before' since the program flow between declaration (in method) and reference is sequential. In case of fields declared outside of the method compiler never knows which code is going to be used when so it cannot generate an error as possibly some other method is going to initialize the field before it is used.
Local variables and primitives should be initialized before use because you would know what to expect from the values. Historically, when a new variable was created it would contain random values from the memory [and one could not predict the value]. Java also requires this because it prevents the presence of orphaned variables.
In practice all variables need to be initialized before using them.
I can't think of a time you'd want to use a variable before setting its value (unless you're comparing it against null).
It is necessary to initialize local variables (only when we use them) because they don't get any default value like instance variables.
And as basic rule, we should always initialize any variable before using it. Otherwise it may result in an error like nullPointer, etc
Now, why don't local variables get default value? The reason is that local variables reside on stack and is visible only in local method context, unlike instance variables which resides on heap and has scope throughout the program.
So when the stack will end local method's value will also get destroyed therefore:
1] They are supposed to be initialized explicitly (when we use them)
2] They should not be initialized implicitly (by null,0 or false) like instance variables
Going by the definition of local variable which state, a local variable is declared within a function or is passed as an argument in a function. If you do not initialized a local variable you will encounter exception handling problem because, the compiler will not be able to understand what value the variable holds
Why must local variables, including primitives, always be initialized in Java? Why is the same not applicable in the case of instance variables?
Basically, requiring a variable to be assigned a value before you read it is a Good Thing. It means you won't accidentally read something you didn't intend to. Yes, variables could have default values - but isn't it better for the compiler to be able to catch your bug instead, if it can prove that you're trying to read something which might not have been assigned yet? If you want to give a local variable a default value, you can always assign that explicitly.
Now that's fine for local variables - but for instance and static variables, the compiler has no way of knowing the order in which methods will be called. Will a property "setter" be called before the "getter"? It has no way of knowing, so it has no way of alerting you to the danger. That's why default values are used for instance/static variables - at least then you'll get a known value (0, false, null etc) instead of just "whatever happened to be in memory at the time." (It also removes the potential security issue of reading sensitive data which hadn't been explicitly wiped.)
There was a question about this very recently for C#... - read the answers there as well, as it's basically the same thing. You might also find Eric Lippert's recent blog post interesting; it's at least around the same area, even though it has a somewhat different thrust.
In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables don't have a default value. Unless a local variable has been assigned a value, the compiler will refuse to compile the code that reads it. IMHO, this leads to the conclusion, that initializing a local variable with some default value (like null, which might lead to a NullPointerException later) when it is declared is actually a bad thing. Consider the following example:
Object o;
if (<some boolean condition>)
o = <some value>;
else
o = <some other value>;
System.out.println(o);
An initialization of o with null is completely unnecessary, since the Java compiler checks at compile time, that any code-path initializes o (with either null or some non-null value) before the variable is read. That means, that the compiler will refuse to compile the line System.out.println(o); if you would comment out any of the two initializations of the variable o in the code snippet above.
This holds for Java, and maybe for Java only. I don't know about language like C#. In good old C (and maybe C++) however, it is still recommended to always initialize variables when declaring them, AFAIK. Such "old-school" programming languages might be the reason, that the recommendation to always initialize variables pops up in books and discussions about modern languages like Java, where the compiler keeps track of whether a variable has been initialized or not.
Not totally true. Local variables only need to be initialized if being reference. A local variable can be left uninitialized if never referenced. For example:
int x; // Valid
int y;
println("y=" + y); // Not valid since y's value has never been assigned
Well, in case of local variable it's clear what it means 'before' since the program flow between declaration (in method) and reference is sequential. In case of fields declared outside of the method compiler never knows which code is going to be used when so it cannot generate an error as possibly some other method is going to initialize the field before it is used.
Local variables and primitives should be initialized before use because you would know what to expect from the values. Historically, when a new variable was created it would contain random values from the memory [and one could not predict the value]. Java also requires this because it prevents the presence of orphaned variables.
In practice all variables need to be initialized before using them.
I can't think of a time you'd want to use a variable before setting its value (unless you're comparing it against null).
It is necessary to initialize local variables (only when we use them) because they don't get any default value like instance variables.
And as basic rule, we should always initialize any variable before using it. Otherwise it may result in an error like nullPointer, etc
Now, why don't local variables get default value? The reason is that local variables reside on stack and is visible only in local method context, unlike instance variables which resides on heap and has scope throughout the program.
So when the stack will end local method's value will also get destroyed therefore:
1] They are supposed to be initialized explicitly (when we use them)
2] They should not be initialized implicitly (by null,0 or false) like instance variables
Going by the definition of local variable which state, a local variable is declared within a function or is passed as an argument in a function. If you do not initialized a local variable you will encounter exception handling problem because, the compiler will not be able to understand what value the variable holds
Why must local variables, including primitives, always be initialized in Java? Why is the same not applicable in the case of instance variables?
Basically, requiring a variable to be assigned a value before you read it is a Good Thing. It means you won't accidentally read something you didn't intend to. Yes, variables could have default values - but isn't it better for the compiler to be able to catch your bug instead, if it can prove that you're trying to read something which might not have been assigned yet? If you want to give a local variable a default value, you can always assign that explicitly.
Now that's fine for local variables - but for instance and static variables, the compiler has no way of knowing the order in which methods will be called. Will a property "setter" be called before the "getter"? It has no way of knowing, so it has no way of alerting you to the danger. That's why default values are used for instance/static variables - at least then you'll get a known value (0, false, null etc) instead of just "whatever happened to be in memory at the time." (It also removes the potential security issue of reading sensitive data which hadn't been explicitly wiped.)
There was a question about this very recently for C#... - read the answers there as well, as it's basically the same thing. You might also find Eric Lippert's recent blog post interesting; it's at least around the same area, even though it has a somewhat different thrust.
In Java, class and instance variables assume a default value (null, 0, false) if they are not initialized manually. However, local variables don't have a default value. Unless a local variable has been assigned a value, the compiler will refuse to compile the code that reads it. IMHO, this leads to the conclusion, that initializing a local variable with some default value (like null, which might lead to a NullPointerException later) when it is declared is actually a bad thing. Consider the following example:
Object o;
if (<some boolean condition>)
o = <some value>;
else
o = <some other value>;
System.out.println(o);
An initialization of o with null is completely unnecessary, since the Java compiler checks at compile time, that any code-path initializes o (with either null or some non-null value) before the variable is read. That means, that the compiler will refuse to compile the line System.out.println(o); if you would comment out any of the two initializations of the variable o in the code snippet above.
This holds for Java, and maybe for Java only. I don't know about language like C#. In good old C (and maybe C++) however, it is still recommended to always initialize variables when declaring them, AFAIK. Such "old-school" programming languages might be the reason, that the recommendation to always initialize variables pops up in books and discussions about modern languages like Java, where the compiler keeps track of whether a variable has been initialized or not.
Not totally true. Local variables only need to be initialized if being reference. A local variable can be left uninitialized if never referenced. For example:
int x; // Valid
int y;
println("y=" + y); // Not valid since y's value has never been assigned
Well, in case of local variable it's clear what it means 'before' since the program flow between declaration (in method) and reference is sequential. In case of fields declared outside of the method compiler never knows which code is going to be used when so it cannot generate an error as possibly some other method is going to initialize the field before it is used.
Local variables and primitives should be initialized before use because you would know what to expect from the values. Historically, when a new variable was created it would contain random values from the memory [and one could not predict the value]. Java also requires this because it prevents the presence of orphaned variables.
In practice all variables need to be initialized before using them.
I can't think of a time you'd want to use a variable before setting its value (unless you're comparing it against null).
It is necessary to initialize local variables (only when we use them) because they don't get any default value like instance variables.
And as basic rule, we should always initialize any variable before using it. Otherwise it may result in an error like nullPointer, etc
Now, why don't local variables get default value? The reason is that local variables reside on stack and is visible only in local method context, unlike instance variables which resides on heap and has scope throughout the program.
So when the stack will end local method's value will also get destroyed therefore:
1] They are supposed to be initialized explicitly (when we use them)
2] They should not be initialized implicitly (by null,0 or false) like instance variables
Going by the definition of local variable which state, a local variable is declared within a function or is passed as an argument in a function. If you do not initialized a local variable you will encounter exception handling problem because, the compiler will not be able to understand what value the variable holds
I have read several previously asked questions and answers on this topic [or quite similar], but none of them have really addressed this point-blank. When declaring a new boolean varibale, is it redundant [e.g. unnecessary] to initialize it to false?
boolean selectedZone = false;
versus just declaring
boolean selectedZone;
The other posts I have looked at are
Why is Java's default value for Boolean set to true? and Default value of Boolean in java
It is redundant in most cases. The exception is if it's a local variable, in which case it needs to be initialized before being used. Examples:
class Example{
boolean value1;//valid, initialized to false
public void doStuff(){
boolean value2;//valid, but uninitialized
System.out.println(value1);//prints "false" (assuming value1 hasn't been changed)
System.out.println(value2);//invalid, because value2 isn't initialized. This line won't compile.
Some documentation on this:
https://web.archive.org/web/20140814175549/https://docs.oracle.com/javase/specs/jls/se5.0/html/typesValues.html#96595
Even though variables are initialized, you still might want to explicitly declare their initial values. It can make the code more legible, and lets people reading your code know that it's a conscious decision to set it to that value.
Related
It is redundant, but I find it clearer.
The same goes for :
int var = 0;
vs.
int var;
I didn't make this up :
Default Values
It's not always necessary to assign a value when a field is declared.
Fields that are declared but not initialized will be set to a
reasonable default by the compiler. Generally speaking, this default
will be zero or null, depending on the data type. Relying on such
default values, however, is generally considered bad programming
style.
The following chart summarizes the default values for the above data
types. Data Type Default Value (for fields) byte 0 short 0 int 0
long 0L float 0.0f double 0.0d char '\u0000' String (or any
object) null boolean false
(Source)
However, as the comments suggest, if it's a local variable, it must be initialized.
Yes, you can skip explicitly initializing it to false - however just because you can doesn't mean you should.
Explicitly setting to false makes code much clearer (and easier for developers coming from other languages where this behaviour is not default).
Fields and array components are initialized to zero, local variables are not. See JLS: http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5