×

Best Practices to use String Class in Java

  1. Use String Builder or String Buffer for String concatenation in place of + operator.
  2. Compare two strings by equals( ) method instead == operator.
  3. Call .equals( ) method on a known String constant rather than unknown variable (“str.equal(variable)).
  4. Create strings as literals (“ “) in place of creating string object using’new’.
  5. Prefer switch( ) statement in place of multiple if else-if.
  6. Using String.valueof( ) in place of toString( )
  7. 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:

Best Practices to use String Class in Java

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:

Best Practices to use String Class in Java

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:

Best Practices to use String Class in Java

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) {}

Related Topics

How to sort an array in Java

Sorting is the process of arranging the elements of a list or array in a specific order, either ascending or descending. The sorting criterion numerical and alphabetical is commonly used...

6 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries. This article will...

4 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

String isnullorempty in Java

What do you mean by String? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

How to Convert Octal to Decimal in Java

How to Convert Octal to Decimal in Java There are two methods to convert Octal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method The Integer.parseInt() method is a static method...

2 minutes read.

Java Byte Code

Java byte code is really a powerful mechanism which makes Java a portable and platform-independent programming language. There are two software components which go along and make this byte code...

3 minutes read.

Hidden classes in Java

There specifically are some APIs available in the market that generally is harmful to be used in our programs specifically literally, and until JDK 15, there, for all intents and...

4 minutes read.

Get yesterdays date by no of days in Java

In this tutorial, we are going to learn how to get yesterday’s date by the no of days in Java. Using the Calendar class, one can get the current date....

1 minute read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.

Nth node from the end of the Linked list in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

6 minutes read.

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

Lazy Propagation in Segment Tree in Java

The topic of segment trees in Java is continued by the topic of sluggish propagation in segment trees. It is suggested that readers first read through the section tree topic....

4 minutes read.

Java Coding Software

Desktop and web apps are created using Java, an object-oriented programming language. Java code may be executed on any platform, making it platform-independent. A text editor, tool, or piece of...

9 minutes read.

Arithmetic exception in Java

Exception Handling is one of the most potent ways of handling runtime faults and preserving the application's normal flow. In Java, an exception is an out-of-the-ordinary state, and exceptions are...

3 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Java Math min() Method

The min() method of Math class returns the smaller of two arguments. The arguments can be of double, float, int or long data type. Syntax: public static double min (double a, double...

2 minutes read.