Reputation: 2500
I have two questions and unfortunately I can't find answers.
If we declare 1000 boolean variables equals to true
will all of them have the same reference to true
literal?
Java is pass-by-value so consider the code
public class Test {
public static boolean global;
public static void main(String[] args) {
foo(false);
System.out.println(global);
}
public static void foo(boolean bar) {
global = bar;
}
}
In foo()
method the primitive value of boolean variable will be copied and it means that global
will have another reference for the literal. Or will Java perform some kind of pool lookup for this and global
will also reference the same memory location as argument?
Upvotes: 4
Views: 1036
Reputation: 3393
Yes, there is a pool. But only if you use Boolean
object instead of boolean
primitive value and if you create it using method valueof
or Boolean.TRUE
/Boolean.FALSE
insteand of a constructor. Check the Boolean javadoc for reference.
Also, take a look to the constructor javadoc. It says:
It is rarely appropriate to use this constructor. Unless a new instance is required, the static factory valueOf(boolean) is generally a better choice. It is likely to yield significantly better space and time performance.
Upvotes: 3