Every time I use String, does it create a new String object?
hashmap, java, string
Solution
No. String constants are interned automatically, so any identical string literals all reference the same object in memory.
Some more information on this: http://www.xyzws.com/Javafaq/what-is-string-literal-pool/3
An example of this:
String s1 = "Test";
String s2 = "Test";
String s3 = new String("Test");
s1 == s2;//Evaluates to true, because they are the same object (both created with string literals)
s1 == s3;//Evaluates to false, because they are different objects containing identical data
Problem
Let's say that I need to iteratively retrieve a value of the same key from a Java hashmap. ``` for(int i=0; i<INTEGER.MAX; i++) map.get("KEY"); ``` In this case, is the "KEY" string created every time I call map.get("KEY")? I was wondering if it's always better to have a String constant, or it doesn't matter.