"Hi, Amigo!"
"Hi, Kim."
"I'm going to tell you about the Boolean type. It's a wrapper for the boolean type, and it's as easy as pie. Here's some simplified code from the Boolean class:"
class Boolean
{
public static final Boolean TRUE = new Boolean(true);
public static final Boolean FALSE = new Boolean(false);
private final boolean value;
public Boolean(boolean value)
{
this.value = value;
}
public boolean booleanValue()
{
return value;
}
public static Boolean valueOf(boolean b)
{
return (b ? TRUE : FALSE);
}
}
"In other words, the class is simply a wrapper for the boolean type."
"Yep. And it has two constants (TRUE and FALSE), which are counterparts of the primitive values true and false."
"It also handles autoboxing like a champ:"
Code | What really happens |
---|---|
|
|
"And here's how comparisons between boolean and Boolean types work:"
boolean a = true;
Boolean b = true; //Will be equal to Boolean.TRUE
Boolean c = true; //Will be equal to Boolean.TRUE
a == b; //true (comparison based on primitive value)
a == c; //true (comparison based on primitive value)
b == c; //true (comparison based on references, but they point to the same object)
"If you really need to create an independent Boolean object, you must create it explicitly:
boolean a = true;
Boolean b = new Boolean(true); //A new Boolean object
Boolean c = true; //Will be equal to Boolean.TRUE
a == b; //true (comparison based on primitive value)
a == c; //true (comparison based on primitive value)
b == c; //false (comparison based on references; they point to different objects)
"I think that's all for now."
"Yeah, your lessons are shorter than Bilaabo's."
"So, can I use Boolean inside an if condition?"
Boolean less = (2 < 3);
if (less)
{
….
}
"Yes, just don't forget that if less is null, then a NullPointerException will be thrown."
"Yep, I already get that. I just don't keep it all in my head all the time."
GO TO FULL VERSION