java 基本型別及包裝類和數值體系

2021-08-30 11:40:27 字數 3226 閱讀 5401

基本型別boolean ,包裝型別boolean,對於基本型別boolean一般使用與分支邏輯判斷,對於boolean型別的分配記憶體空間,有1個或4個的位元組的不同定義,在編譯後boolean被int型別資料替換,boolean型別陣列被替換成byte陣列,可能的儲存空間有1或4個位元組。

boolean型別:

boolean類中有四個屬性,其中兩個boolean型的類屬性

/**

* the object corresponding to the primitive

* value .

/public static final boolean true = new boolean(true);

/** the object corresponding to the primitive

* value .

*/public static final boolean false = new boolean(false);

乙個type型別的類屬性

/**

* the class object representing the primitive type boolean.

** @since jdk1.1

*/public static final class type = class.getprimitiveclass(「boolean」);

乙個final的boolean型別成員屬性

/**

* the class object representing the primitive type boolean.

** @since jdk1.1

*/public static final class type = class.getprimitiveclass(「boolean」);

構造器:

簡單的傳boolean型構造方式

public boolean(boolean value)

和使用boolean字串的方式

public boolean(string s)

private static boolean toboolean(string name)

傳入"true"不區分大小寫都會建立value為true的boolean物件。

基本api:

public static boolean parseboolean(string s)

將字串轉成boolean型別,非「true」不區分大小寫都為false。可用於string和boolean型別轉換。

public boolean booleanvalue()

等同於其他物件的getter。取boolean物件的value

public static boolean valueof(boolean b)

把基本boolean型別包裝成boolean型別,由於boolean類屬性中已經有了true和false,所以把boolean基本型別包裝成boolean型別的時候推薦使用這種方法,避免建立新的物件,而且對計算沒有影響。

public static boolean valueof(string s)

通過字元型別建立boolean型別,"true"不區分大小建立true否則false

public static string tostring(boolean b)

public string tostring()

兩個tostring方法,乙個類的靜態方法,乙個物件的方法都是值為true返回「true」為false返回「false」

public int hashcode()

public boolean equals(object obj)

return false;

}

重寫了hashcode()和equals方法,1231和1237是兩個比較大的素數能避免雜湊碰撞,equals改為比較boolean物件的value是否一致。

public static boolean getboolean(string name) catch (illegalargumentexception e) catch (nullpointerexception e)

return result;

}

只有在系統中有環境變數name且name為「true」不區分大小寫的時候才會返回true,不只到具體的用途在**。

public int compareto(boolean b)

public static int compare(boolean x, boolean y)

boolean實現了comparable介面,value相同返回0,否則認為true>false,即x=true,y=false 返回1;

小結

在實際的使用中一般使用boolean基本型別就可以了,很少用到過boolean物件和boolean的靜態方法,由boolean型別或string型別建立的時候盡量使用boolean的valueof方法,建立包裝類。

原始型別

目標型別

apiboolean

boolean

static boolean valueof(boolean b)

string

boolean

static boolean valueof(boolean b)

boolean

boolean

boolean booleanvalue()

string

boolean

static boolean parseboolean(string s)

boolean

string

static string tostring(boolean b)

boolean

string

string tostring()

JAVA基本型別與包裝類

1.宣告方式不同,基本型別不適用new關鍵字,而包裝型別需要使用new關鍵字來在堆中分配儲存空間 2.儲存方式及位置不同,基本型別 區域性變數在棧中,成員變數實在堆中,靜態變數在data區中 是直接將變數值儲存在棧中,而包裝型別是將物件放在堆中,然後通過引用來使用 3.初始值不同,基本型別的初始值如...

基本型別包裝類

一 概述 1 將基本資料型別封裝成物件的好處在於可以在物件中定義更多的功能方法操作該資料。2 常用的操作之一 用於基本資料型別與字串之間的轉換。3 基本型別和包裝類的對應 byte,short,integer,long,float,double character,boolean 二 integer...

基本型別包裝類

基本資料型別的包裝類可以使用基本型別對應的類的相關成員變數和成員方法,相比於基本資料型別,包裝類更易於使用。八大基本資料型別 byte short int long float double char boolean 對應的包裝類 byte short integer long float doub...