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

Java – How null works with StringBuffer

By Chaitanya Singh | Filed Under: StringBuffer

You should be careful while appending nulls to StringBuffer as it may result in the unexpected output (if you are not aware how null works with StringBuffer). When you append null to StringBuffer, it actually appends four character string (“null”) to the buffer instead of an empty string. Let’s take an example to see this behavior.

public class StringBufferNullExample {
   public static void main(String args[])
   {
	String str = null;
	StringBuffer sb = new StringBuffer();
	sb.append(str);
	System.out.println("Length: "+sb.length());
	System.out.println("Content: "+sb);
   }
}

Output:

Length: 4
Content: null

As you can see that the length of StringBuffer is 4 after we appended null to it. It is easy to identify and handle null in above example but it may be headache for you when you are not sure about the value of the strings that you are appending to StringBuffer, for example when we are taking the string value from user as an input in that case it depends on the user what he is going to enter. To avoid such issues we must need to do a null check before appending strings to the StringBuffer. This is how we can do this:

if (str != null) sb.append(str);

By doing this you are ensuring that no null values are going to be inserted into the StringBuffer.

Enjoyed this post? Try these related posts

  1. Java – How to append a newline to StringBuffer
  2. Difference between String and StringBuffer
  3. StringBuffer substring method Example
  4. StringBuffer Replace method Example
  5. 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