×

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

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.

Difference between Aggregation and Composition in Java

What is Aggregation? Before we start discussing Aggregation, we have to know some general information about our classes in java. Generally we have two members in our classes , the first...

8 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters....

6 minutes read.

Java String Reader

StreamReaderClass: This class is present in the java.io package. It is a character stream in which string act as a source.This method provides to read characters from a string. Character Stream: This class...

3 minutes read.

Java RandomAccessfile

Writing and reading to random access files are done using this class. An array of many bytes is how a random access file operates. By changing the implied file pointer...

3 minutes read.

Check whether a Number is a Power of 4 or Not in Java

There are many ways to figure out if an integer is a power of 4. This section will go over a variety of techniques for figuring out whether or not...

11 minutes read.

Upcasting in Java

To know what is Upcasting in Java we should first equip ourselves about what is casting or type casting in Java. Casting The process of providing or replacing a reference variable of...

3 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

Difference between print() and println() in Java

In this tutorial, we will discuss the differences between print and println in Java language. There are mainly two methods to display the text on the console printprintln The above two methods are...

4 minutes read.

Sorting a String in Java

Sorting a String in Java Sorting is a process of arranging available data objects in a meaningful format that is ascending or descending order. Sorting a string or array of String...

4 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Java Try Resource

In Java, a try argument that specifies one or more resources is known as a try-with-resources statement. When your program is finished utilizing an object, it must be closed, which...

4 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

Java Protected Keyword

An access modifier is a keyword that Java protects. It can be used to constructors, methods, inner classes, and variables. Variables, methods, and constructors that have been marked protected in...

3 minutes read.

Java Map Interface

A map is a collection that maps keys to values, with no duplicate keys allowed. The elements in a map are key/value pairs. HashMap: HashMap stores the keys in a...

3 minutes read.

Jdoodle Java

Everything is instantaneous and fast-paced in the modern world. Online compilers available via the internet are immensely helpful for programmers seeking to learn a new programming language but lacking the...

4 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

C# vs Java

Difference Between C# and Java C# and Java both languagesare popularly used programming languages. They both are derived from C/C++ programming and follow Object Oriented Programming approach. Even so, both these...

4 minutes read.