目錄
基本數據類型的字節與位數如下:
- 變量名稱 字節 位數
- byte 1 8
- short 2 16
- int 4 32
- long 8 64
- float 4 32
- double 8 64
- char 2 16
- boolean 1 8
String類型的最大長度
在cpp中爲了可移植性,string的長度是string::size_type,突然就想知道java允許的最大字符串長度爲多少。看String的源碼:
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence
{
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
String內部是以char數組的形式存儲,數組的長度是int類型,那麼String允許的最大長度就是Integer.MAX_VALUE了。又由於java中的字符是以16位存儲的,因此大概需要4GB的內存才能存儲最大長度的字符串。不過這僅僅是對字符串變量而言,如果是字符串字面量(string literals),如“abc"、"1a2b"之類寫在代碼中的字符串literals,那麼允許的最大長度取決於字符串在常量池中的存儲大小,也就是字符串在class格式文件中的存儲格式:
CONSTANT_Utf8_info {
u1 tag;
u2 length;
u1 bytes[length];
}
- u2是無符號的16位整數,因此理論上允許的string literal的最大長度是2^16=65536。然而實際測試表明,允許的最大長度僅爲65534,超過就編譯錯誤了,有興趣可以寫段代碼試試。
部分內容參考:https://blog.csdn.net/mycs2012/article/details/95715799