目录
基本数据类型的字节与位数如下:
- 变量名称 字节 位数
- 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
本文探讨了Java和C++中字符串的最大长度限制。在Java中,字符串长度受int类型限制,理论上可达Integer.MAX_VALUE,需4GB内存;而C++中的string长度由string::size_type决定,具有较好的移植性。对于Java字符串字面量,其最大长度受UTF-8编码限制,实际测试最大为65534。
6333

被折叠的 条评论
为什么被折叠?



