"will two strings with same content be stored in the same memory location?" Code Answer


the process of combining identical strings is called "interning", and has been done for many years by lots of language compilers, but not always. the answer to the question, especially as expanded by @gennadyvanin--novosibirsk, depends on the language and the compiler implementation. for java, all constant strings are interned, as required by the java language specification. but that's only constant string expressions, and only when they're compiled at the same time. if you have two java strings sufficiently separated in time and space (e.g., compiled into separate jar files), they will not be the same object. similarly, dynamically created java strings (e.g., the output of various tostring() methods) won't be interned unless the method specifically requests it via string.intern(). and yes, all uses of an interned string will share the same memory locations - that's a big part of why strings are interned in the first place.

as to other languages, that's a bigger question, but with all the information in these answers, i'm sure you can research it on the web. suffice it to say that there is no universal agreement on how this ought to be done.

By andrei.ciprian on March 31 2022

Answers related to “will two strings with same content be stored in the same memory location?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.