Best Practices to use String Class in Java
- Use String Builder or String Buffer for String concatenation in place of + operator.
- Compare two strings by equals( ) method instead == operator.
- Call .equals( ) method on a known String constant rather than unknown variable (“str.equal(variable)).
- Create strings as literals (“ “) in place of creating string object using’new’.
- Prefer switch( ) statement in place of multiple if else-if.
- Using String.valueof( ) in place of toString( )
- Using string utility class from well-known third party libraries.
Use StringBuilder or StringBuffer for string concatenations instead of the + operator
If you often concatenate strings, the StringBuilder object is preferable than the + operator.
As it has the similar methods as StringBuilder but with synchronized execution, StringBuffer behaves similarly. That means multi-threading situations call for the employment of StringBuffer.
Let's create a straightforward application to show how well String, StringBuilder, and StringBuffer perform.
public class PerformanceTest¬¬{
public static void main(String []args){
String str = "";
long startTime = System.microTime();
for(int i=0 ; i < 10 ; i++) {
str = str + i;
}
long endTime = System.microTime();
System.out.println(String.format("String operation with
+ operator took [%d] micro seconds",(endTime-startTime)));
StringBuilder builder = new StringBuilder();
startTime = System.microTime();
for(int i=0;i<10;i++) {
builder.append(i);
}
endTime = System.microTime();
System.out.println(String.format("String operation with
StringBuilder took [%d] micro seconds",(endTime-startTime)));
StringBuffer strBuffer = new StringBuffer();
startTime = System.microTime();
for(int i=0;i<10;i++) {
strBuffer.append(i);
}
endTime = System.microTime();
System.out.println(String.format("String operation with
StringBuffer took [%d] micro seconds",(endTime-startTime)));
}
}
Output:

As you can see from the results, string concatenation using the StringBuilder and StringBuffer methods is quicker as compared to use the + operator.
Note: Did you know that '+' String concatenations may be automatically converted to StringBuilder append()s in Eclipse? Additionally, it chooses the appropriate add() for each type. Ctrl+1 is quite useful.
Compare two Strings by equals() method in place of “==” operator
When we will compare string contents and string references, keep in mind the considerations below:
- When comparing primitives in Java, such as booleans, ints, and chars, use == rather than equals().
- When two references to the same object are made, "==" returns true. The altered implementation determines the equals() method's output.
- Instead of the == equality operator, use equals() to compare the contents of two Strings.
public class StringEqualsTest{
public static void main(String []args){
String s1 = "stringjava";
String s2 = "stringjava";
String s3 = new String("stringjava");
System.out.println(" ‘==’ operator gives the result for s1 and s2 : " + (s1 == s2));
System.out.println(" ‘==’ operator gives the result for s1 and s3 : " + (s1 == s3));
System.out.println(" equals() method gives the result for s1 and s2 : " + s1.equals(s2));
System.out.println(" equals() method gives the result for s1 and s3 : " + s1.equals(s3));
}
}
Output:

Call .equals( ) method on a known String constant rather than unknown variable (“str.equal(variable)).
Use the equals technique on known constants rather than an unknown variable if you are aware that some constants are fixed. Variables may occasionally contain null, and using the equals function on one of these variables will result in a null pointer error.
public class ConstantEqualsTest{
private static final String CONSTANT = "constant value";
public static void main(String []args){
processString("constant value");
}
private static void processString(String str){
if(CONSTANT.equals(str)){
System.out.println("CONSTANT.equals(string): "
+ CONSTANT.equals(str));
}
}
}
Output:

Prefer switch() statement in place of multiple if else-if.
The switch statement for Strings is new in Java 1.7. When comparing many strings, utilize switches rather than numerous if-else-if expressions.
Use of String.valueOf() in place of toString()
The results of obj.toString() and String.valueOf(obj) are identical when an object has to be converted to a string, but String.valueOf() is null safe and never raises a NullPointerException.
Use String Utility Classes
Choose StringUtility classes from many well-known libraries instead of other classes since these libraries have been tried and true.
Avoid Duplicate Literals
It is typically better code to declare the String as a constant field rather than having redundant String literals.
private void bar() {
String canja= "Canja"
buz(canja);
buz(canja);
}
private void buz(String x) {}
// Better
private static final String CANJA = "Canja";
private void bar() {
buz(CANJA);
buz(CANJA);
}
private void buz(String x) {}