Java String is widely used in Java application development to store data. An integer, a float point number, a character, a date, an array…all can be represented by a String. So it’s really importance if you study all thing related to Java String and best practice when using it.
1. Java String is immutable.
This means the String object is read-only when the object has been created. You cannot change it anymore.
String string1 = "Hello World this is Java String, it cannot be changed after created";
2. Java String literal is a reference to a String object
This means you can call method of Java String class with a String literal like below:
int strLength = "Java String".length();
3. String concatenate
You can concat Java String like I do below:
String result = "Java" + "String" + "is" + "Immutable";
But the problem is that Java String is Immutable, that mean when you concatenate like above, new String object will be created for each + operator. “Java” is an object and “String” is another object, if “Java” + “String” then it generate another object equals to “Java String”…and this continues if there are more plus (+) operators.
So what is the best practice here? Use StringBuilder instead (you may hear of StringBuffer but I don’t recommend you to use it, maybe I will show why later). OK you should concatenate String as below: