Strings - AnsuDennis/Java GitHub Wiki

String objects in Java are immutable. Any modifications on the object will create a new String object. The location where the string values are stored in memory depends on how we create them.

Methods concat, replace, toLowerCase, toUpperCase or substring methods will create a new string and return that value.

Approach 1 In the example below we are directly referencing a String literal. String str1 = "value";

This value will be stored in a "String constant pool" – which is inside the Heap memory. If compiler finds a String literal,it checks if it exists in the pool. If it exists, it is reused.

String str5 = "value"; In above example, when str5 is created - the existing value from String Constant Pool is reused.

Approach 2 However, if new operator is used to create string object, the new object is created on the heap. There will not be any reuse of values.

//String Object - created on the heap String str2 = new String("value");

So we should not use new operator while working with String. Also we should be careful about String Concatenation(+) operator in Loops due to the above reason. Instead of String u should use StringBuffer(thread safe) or StringBuilder(not thread safe) which will not create new objects.

Differences between String and StringBuffer • Objects of type String are immutable. StringBuffer is used to represent values that can be modified. • In situations where values are modified a number to times, StringBuffer yields significant performance benefits. • Both String and StringBuffer are thread-safe. • StringBuffer is implemented by using synchronized keyword on all methods.

StringBuilder is not thread safe. So, it performs better in situations where thread safety is not required.