What is the difference between String x="hello"; and String x=new String("hello") in terms of the object creation and the reference. Is there any difference in the way memory is allocated for these two type of String declarations.
Hi, Welcome to JavaRanch! In the first case (without the new) the String comes from a pool of unique strings held internally by the JVM; literal Strings are put into this pool when the classes defining them are loaded. In the second case, a new String object is allocated at that point while the program is executing.
All string constants are dumped into the CONSTANT_POOL at compile time. In the following example:
When this compiles there are two string constants placed in the constant pool, one for "A string" and one for "B string". However at runtime both 'one' and 'two' would reference the same string, while new string instances would be created for 'three', 'four' and 'five', as Ernest pointed out. So "one == two" would evaluate to "true", but any other combination of strings would evaluate to "false" when doing an "==". That's why it's always safest to use ".equals()" when doing string comparison, unless you actually want to see if the two strings reference the same underlying String instance.