“สวัสดี อามีโก้!”
"สวัสดีคิม"
"ฉันจะบอกคุณเกี่ยวกับประเภทบูลีน มันเป็นตัวห่อหุ้มสำหรับประเภทบูลีน และมันก็ง่ายเหมือนพาย ต่อไปนี้คือโค้ดง่ายๆ จากคลาสบูลีน:"
รหัส
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);
}
}
"อีกนัยหนึ่ง คลาสเป็นเพียงตัวห่อหุ้มสำหรับประเภทบูลีน"
"ใช่ และมีค่าคงที่สองค่า (จริงและเท็จ) ซึ่งเป็นคู่ของค่าดั้งเดิมจริงและเท็จ"
"มันยังจัดการ autoboxing เหมือนแชมป์:"
รหัส | เกิดอะไรขึ้นจริงๆ |
---|---|
|
|
"และนี่คือวิธีการเปรียบเทียบระหว่างประเภทบูลีนและบูลีน:"
ตัวอย่าง
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)
"ถ้าคุณต้องการสร้างวัตถุบูลีนอิสระ คุณต้องสร้างอย่างชัดเจน:
ตัวอย่าง
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)
"ฉันคิดว่านั่นคือทั้งหมดสำหรับตอนนี้"
"ใช่ บทเรียนของคุณสั้นกว่าของ Bilaabo"
"ดังนั้นฉันสามารถใช้บูลีนในเงื่อนไข if ได้หรือไม่"
Boolean less = (2 < 3);
if (less)
{
….
}
"ใช่ อย่าลืมว่าถ้าค่าน้อยเป็นโมฆะ NullPointerException จะถูกส่งออกไป"
"ใช่ ฉันเข้าใจแล้ว ฉันแค่ไม่เก็บมันไว้ในหัวตลอดเวลา"
GO TO FULL VERSION