Is setting a boolean to false redundant? - java

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

Related

how to declare variable such that it don't give any error in java [duplicate]

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

The variable not have been initialized of the java class [duplicate]

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

Java - Why variable initialization is important [duplicate]

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

For boolean fields in Java Model class is it better to use Boolean object or primitive boolean field [duplicate]

There are discussions around Integer vs int in Java. The default value of the former is null while in the latter it's 0. How about Boolean vs boolean?
A variable in my application can have 0/1 values. I would like to use boolean/Boolean and prefer not to use int. Can I use Boolean/boolean instead?
Yes you can use Boolean/boolean instead.
First one is Object and second one is primitive type.
On first one, you will get more methods which will be useful.
Second one is cheap considering memory expense The second will save you a lot more memory, so go for it
Now choose your way.
Boolean wraps the boolean primitive type. In JDK 5 and upwards, Oracle (or Sun before Oracle bought them) introduced autoboxing/unboxing, which essentially allows you to do this
boolean result = Boolean.TRUE;
or
Boolean result = true;
Which essentially the compiler does,
Boolean result = Boolean.valueOf(true);
So, for your answer, it's YES.
I am a bit extending provided answers (since so far they concentrate on their "own"/artificial terminology focusing on programming a particular language instead of taking care of the bigger picture behind the scene of creating the programming languages, in general, i.e. when things like type-safety vs. memory considerations make the difference):
int is not boolean
Consider
boolean bar = true;
System.out.printf("Bar is %b\n", bar);
System.out.printf("Bar is %d\n", (bar)?1:0);
int baz = 1;
System.out.printf("Baz is %d\n", baz);
System.out.printf("Baz is %b\n", baz);
with output
Bar is true
Bar is 1
Baz is 1
Baz is true
Java code on 3rd line (bar)?1:0 illustrates that bar (boolean) cannot be implicitly converted (casted) into an int. I am bringing this up not to illustrate the details of implementation behind JVM, but to point out that in terms of low level considerations (as memory size) one does have to prefer values over type safety. Especially if that type safety is not truly/fully used as in boolean types where checks are done in form of
if value \in {0,1} then cast to boolean type, otherwise throw an exception.
All just to state that {0,1} < {-2^31, .. , 2^31 -1}. Seems like an overkill, right? Type safety is truly important in user defined types, not in implicit casting of primitives (although last are included in the first).
Bytes are not types or bits
Note that in memory your variable from range of {0,1} will still occupy at least a byte or a word (xbits depending on the size of the register) unless specially taken care of (e.g. packed nicely in memory - 8 "boolean" bits into 1 byte - back and forth).
By preferring type safety (as in putting/wrapping value into a box of a particular type) over extra value packing (e.g. using bit shifts or arithmetic), one does effectively chooses writing less code over gaining more memory. (On the other hand one can always define a custom user type which will facilitate all the conversion not worth than Boolean).
keyword vs. type
Finally, your question is about comparing keyword vs. type. I believe it is important to explain why or how exactly you will get performance by using/preferring keywords ("marked" as primitive) over types (normal composite user-definable classes using another keyword class)
or in other words
boolean foo = true;
vs.
Boolean foo = true;
The first "thing" (type) can not be extended (subclassed) and not without a reason. Effectively Java terminology of primitive and wrapping classes can be simply translated into inline value (a LITERAL or a constant that gets directly substituted by compiler whenever it is possible to infer the substitution or if not - still fallback into wrapping the value).
Optimization is achieved due to trivial:
"Less runtime casting operations => more speed."
That is why when the actual type inference is done it may (still) end up in instantiating of wrapping class with all the type information if necessary (or converting/casting into such).
So, the difference between boolean and Boolean is exactly in Compilation and Runtime (a bit far going but almost as instanceof vs. getClass()).
Finally, autoboxing is slower than primitives
Note the fact that Java can do autoboxing is just a "syntactic sugar". It does not speed up anything, just allows you to write less code. That's it. Casting and wrapping into type information container is still performed. For performance reasons choose arithmetics which will always skip extra housekeeping of creating class instances with type information to implement type safety. Lack of type safety is the price you pay to gain performance. For code with boolean-valued expressions type safety (when you write less and hence implicit code) would be critical e.g. for if-then-else flow controls.
You can use the Boolean constants - Boolean.TRUE and Boolean.FALSE instead of 0 and 1. You can create your variable as of type boolean if primitive is what you are after. This way you won't have to create new Boolean objects.
One observation: (though this can be thought of side effect)
boolean being a primitive can either say yes or no.
Boolean is an object (it can refer to either yes or no or 'don't know' i.e. null)
Basically boolean represent a primitive data type where Boolean represent a reference data type. this story is started when Java want to become purely object oriented it's provided wrapper class concept to over come to use of primitive data type.
boolean b1;
Boolean b2;
b1 and b2 are not same.
You can use Boolean / boolean. Simplicity is the way to go.
If you do not need specific api (Collections, Streams, etc.) and you are not foreseeing that you will need them - use primitive version of it (boolean).
With primitives you guarantee that you will not pass null values. You will not fall in traps like this. The code below throws NullPointerException (from: Booleans, conditional operators and autoboxing):
public static void main(String[] args) throws Exception {
Boolean b = true ? returnsNull() : false; // NPE on this line.
System.out.println(b);
}
public static Boolean returnsNull() {
return null;
}
Use Boolean when you need an object, eg:
Stream of Booleans,
Optional
Collections of Booleans
Boolean is threadsafe, so you can consider this factor as well along with all other listed in answers

Default Boolean value in Java [duplicate]

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.

Categories