String是不可变类,当然是从构造函数来的,实现原理就去源码看构造函数: public String() { this.offset = 0; this.count = 0; this.value = new char[0]; }public String(String original) { int size = original.count; char[] originalValue = original.value; char[] v; if (originalValue.length > size) { // The array representing the String is bigger than the new // String itself. Perhaps this constructor is being called // in order to trim the baggage, so make a copy of the array. int off = original.offset; v = Arrays.copyOfRange(originalValue, off, off+size); } else { // The array representing the String is the same // size as the String, so no point in making a copy. v = originalValue; } this.offset = 0; this.count = size; this.value = v; } public String(char value[]) { this.offset = 0; this.count = value.length; this.value = StringValue.from(value); } public String(char value[], int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count < 0) { throw new StringIndexOutOfBoundsException(count); } // Note: offset or count might be near -1>>>1. if (offset > value.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } this.offset = 0; this.count = count; this.value = Arrays.copyOfRange(value, offset, offset+count); }
int length(const char *str) {
int len = 0;
while (*str++) {
++len;
} return len;
}
return count;
}
虚拟机不会提供方法处理,只会解析java指令,内存更不可能自己处理,只是存储而已
String类内部是用字符数组保存数据的,长度就直接取该数组的长度
int len = 0;
while (*str++) {
++len;
} return len;
}
String是不可变类,当然是从构造函数来的,实现原理就去源码看构造函数:
public String() {
this.offset = 0;
this.count = 0;
this.value = new char[0];
}public String(String original) {
int size = original.count;
char[] originalValue = original.value;
char[] v;
if (originalValue.length > size) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
int off = original.offset;
v = Arrays.copyOfRange(originalValue, off, off+size);
} else {
// The array representing the String is the same
// size as the String, so no point in making a copy.
v = originalValue;
}
this.offset = 0;
this.count = size;
this.value = v;
} public String(char value[]) {
this.offset = 0;
this.count = value.length;
this.value = StringValue.from(value);
}
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
// Note: offset or count might be near -1>>>1.
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
this.offset = 0;
this.count = count;
this.value = Arrays.copyOfRange(value, offset, offset+count);
}