I have been trying to understand how some of API methods work
below is a snippet of equals method of java.lang.String class
Can someone out there tell me how
As you may be knowing that string handling in Java is a special case, most of the time the String is assigned from the String pools, so it might be the case that for a char array "I am Learning Java", one string reference points to "I am Learning Java", then offset would be 0, other string might point to "am" so offset would be 2. As some of the native code handles its initilization so i think offset is set during that process.(during sharing memory from String pool)
Also as you can see from the code
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;
}
When new String is created from the old one, it might be the case that old string(original in this case) might be from String pool, thats why first a offset is taken and then the whole array is copied to allocate new memory(new string doesn't share memory from String pool)
Also you should remember String is a derived type and the string is always stored in a character array, so we need an offset to determine from where the string starts in the character array.