1.

How Are Strings Represented In Memory?

Answer»

A String instance in Java is an object with two fields: a char[] value field and an int hash field. The value field is an ARRAY of chars representing the string itself, and the hash field contains the hashCode of a string which is initialized with ZERO, calculated during the FIRST hashCode() call and cached ever since. As a curious edge case, if a hashCode of a string has a zero value, it has to be recalculated each time the hashCode() is called.

IMPORTANT THING is that a String instance is immutable:

  • you can’t get or modify the underlying char[] array. Another feature of strings is that the static constant strings are loaded and cached in a string pool.
  • If you have multiple identical String objects in your source code, they are all represented by a single instance at runtime.

A String instance in Java is an object with two fields: a char[] value field and an int hash field. The value field is an array of chars representing the string itself, and the hash field contains the hashCode of a string which is initialized with zero, calculated during the first hashCode() call and cached ever since. As a curious edge case, if a hashCode of a string has a zero value, it has to be recalculated each time the hashCode() is called.

Important thing is that a String instance is immutable:



Discussion

No Comment Found