Problem Questions
Problem 1 Are all String’s immutable?
Problem 2 Where are string values stored in memory?
Problem 3 Why should you be careful about String Concatenation(+) operator in Loops?
Problem 4 How do you solve above problem?
Problem 5 What are differences between String and StringBuffer?
Problem 6 What are differences between StringBuilder and StringBuffer?
Problem 7 Can you give examples of different utility methods in String class?

Are all String’s immutable?

Value of a String Object once created cannot be modified. Any modification on a 
String object creates a new String object.

String str3 = "value1";
str3.concat("value2");
System.out.println(str3); //value1

**Note that the value of str3 is not modified in the above example. The result 
should be assigned to a new reference variable (or same variable can be reused).
All wrapper class instances are immutable too!**

String concat = str3.concat("value2");
System.out.println(concat); //value1value2

Where are string values stored in memory?

The location where the string values are stored in memory depends on how we 
create them.

**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");

Why should you be careful about String Concatenation(+) operator in Loops?

Consider the code below:

String s3 = "Value1";
String s2 = "Value2";

for (int i = 0; i < 100000; ++i) {
		s3 = s3 + s2;
}

How many objects are created in memory? More than 100000 Strings are created. 
This will have a huge performance impact.

How do you solve above problem?

The easiest way to solve above problem is using StringBuffer. On my machine 
StringBuffer version took 0.5 seconds. String version took 25 Seconds. That’s a 
50 fold increase in performance.

StringBuffer s3 = new StringBuffer("Value1");
String s2 = "Value2";

for (int i = 0; i < 100000; ++i) {
	s3.append(s2);
}

Untitled

What are differences between String and StringBuffer?