beginnersbook.com

  • Home
  • All Tutorials
    • Learn Servlet
    • Learn JSP
    • Learn JSTL
    • Learn C
    • Learn C++
    • Learn MongoDB
    • Learn XML
    • Learn Python
    • Learn Perl
    • Learn Kotlin
  • Core Java
  • OOPs
  • Collections
  • Java I/O
  • JSON
  • DBMS

StringBuilder append() null values as “null” String

By Chaitanya Singh | Filed Under: StringBuilder

While working with StringBuilder you may have come across a strange behavior of append() method for null values. If you append a null value to the StringBuilder object, it would be stored as a “null” (four character string) in the object instead of no value at all. Lets take an example to understand what I stated above.

Problem

class AppendNullDemo{ 
  public static void main(String args[]){ 
 
     // String array with few null elements
     String str[] = {" Mango ", null, " Orange ", " Banana ", null};
 
     // Create StringBuilder object
     StringBuilder sb = new StringBuilder();
 
     for (String temp: str){
        sb.append(temp);
     }
 
     // Displaying the output
     System.out.println(sb);
  } 
}

Output:

 Mango null Orange  Banana null

As you can see that null values are appended as “null” strings in the output, however we prefer to have no values for the null elements. The fix of this issue is provided in the next program.

Solution:

Here is the solution of above issue.

class AdppendNullSolution{ 
  public static void main(String args[]){ 
 
     // String array with few null elements
     String str[] = {" Mango ", null, " Orange ", " Banana ", null};
 
     // Create StringBuilder object
     StringBuilder sb = new StringBuilder();
 
     for (String temp: str){
        // Append only when the string is not null
        if (temp != null)
        {
           sb.append(temp);
        }
     }
  
     // Displaying the output
     System.out.println(sb);
  } 
}

Output:

 Mango  Orange  Banana

Issue fixed: Null Strings are eliminated from the output.

The reason of the issue?

The reason is explained in the documentation of the append() method from javadoc:
public StringBuilder append(String str): Appends the specified string to this character sequence.
The characters of the String argument are appended, in order, increasing the length of this sequence by the length of the argument. If str is null, then the four characters “null” are appended.

Enjoyed this post? Try these related posts

  1. How to append a newline to StringBuilder
  2. Difference between StringBuilder and StringBuffer

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recently Added..

  • JSON Tutorial
  • Java Regular Expressions Tutorial
  • Java Enum Tutorial
  • Java Annotations Tutorial

Copyright © 2012 – 2021 BeginnersBook . Privacy Policy . Sitemap