CodeGym/Java Blog/Strings in Java/Append() Method in Java: StringBuilder and StringBuffer
Author
Volodymyr Portianko
Java Engineer at Playtika

Append() Method in Java: StringBuilder and StringBuffer

Published in the Strings in Java group
members
append() is a Java method of StringBuilder and StringBuffer classes that appends some value to a current sequence. Even if you didn't know what the append() method is, you probably already used it implicitly. This happened when you concatenated Strings in Java using the + operator. The point is that String concatenation in Java is implemented using the StringBuilder or StringBuffer class and their append() method.

Very Briefly about String, StringBuffer and StringBuilder

As you probably know String class is final (it has no child classes) and immutable (instances of this class cannot be modified after creation). In fact, due to the immutability of the String class, new string instances are created as a result of each operation, and old ones are discarded, generating a lot of garbage. To deal with the generation of temporary garbage due to modifications to the String object, you can use the StringBuffer or StringBuilder classes. The main difference between the latter two is that StringBuffer is Synchronized while StringBuilder is not. Hence, use StringBuffer for strings that will be modified frequently in a multi-threaded environment and StringBuilder in case of a single-threaded environment.Append() Method in Java: StringBuilder and StringBuffer - 1

Append() in StringBuilder and StringBuffer

append() is one of the top methods of StringBuilder and StringBuffer classes. It appends a new value to the current sequence. There are 13 various overloaded append() methods in both StringBuffer and StringBuilder classes. Let’s look at the append method for StringBuilder. Anyway, they work exactly the same in case of StringBuffer.
  • public StringBuilder append(boolean b)
  • public StringBuilder append(char c)
  • public StringBuilder append(char[] str)
  • public StringBuilder append(char[] str, int offset, int len)
  • public StringBuilder append(CharSequence cs)
  • public StringBuilder append(CharSequence cs, int start, int end)
  • public StringBuilder append(double d)
  • public StringBuilder append(float f)
  • public StringBuilder append(int i)
  • public StringBuilder append(long lng)
  • public StringBuilder append(Object obj)
  • public StringBuilder append(String str)
  • public StringBuilder append(StringBuffer sb)
Let’s go over some of them and explain with examples what exactly the append() method does.

Java.lang.StringBuilder.append(int i)

java.lang.StringBuilder.append(int i) is a method that allows appending an integer to an existing StringBuilder object. Let’s take a look at the examples of using Java.lang.StringBuilder.append(int i):
StringBuilder s = new StringBuilder(I love Java);
int i = 14;
//the method appends StringBuilder and integer
s.append(i);
System.out.println(s);
The output here will be:
I love Java 14
What happened here? First, we created a StringBuilder named s with the value "I love Java". Then added to it an integer 14 using append(int). Strictly speaking, we added not an integer, but the string "14" and got an updated StringBuilder value to "I love Java 14". Thus, the method turns the argument into a StringBuilder object, binds it to an existing StringBuilder object, and returns an updated one.

StringBuilder append() example for Object, int, boolean and String argument

The same story will be with all the other overloaded methods with number, string, char or arrays elements. Let’s create a LegoBrick Class and Color enum to demonstrate the public StringBuilder append(Object obj) method.
//enum with colors
 public enum Color {
   RED, YELLOW, BLUE;
}
//LegoBrick Class code
public class LegoBrick {
   Color color;
   boolean isConnected;

   public void connect() {
       System.out.println("This brick is connected");
       this.isConnected = true;
   }

   public void disconnect() {
       System.out.println("Disconnected");
       isConnected = false;
   }

   public LegoBrick(Color color, boolean isConnected) {
       this.color = color;
       this.isConnected = isConnected;
   }

   public Color getColor() {
       return color;
   }

   public boolean isConnected() {
       return isConnected;
   }

   @Override
   public String toString() {
       return "LegoBrick{" +
              "color=" + color +
              ", isConnected=" + isConnected +
              '}';
   }
}
Now let’s create an AppendDemo Class where we will show appending of a basic StringBuilder with String, int, LegoBrick and boolean. Sounds weird, but it works!
public class AppendDemo {

   public static void main(String[] args) {
       StringBuilder s = new StringBuilder("I love");
System.out.println(s)
//the method appends StringBuilder and String
       s.append(" Java");
       System.out.println(s);
//the method appends StringBuilder and int
       s.append(14);
       System.out.println(s);
       LegoBrick legoBrick = new LegoBrick(Color.RED, false);
//the method appends StringBuilder and LegoBrick
       s.append(legoBrick);
       System.out.println(s);
//the method appends StringBuilder and boolean
       System.out.println(s.append(5<7));
   }
}
The output is:
I love I love Java I love Java14 I love Java14LegoBrick{color=RED, isConnected=false} I love Java14LegoBrick{color=RED, isConnected=false}true
First, we created and displayed StringBuilder "I love", then First, wethen sequentially added to it using append() method a String, an int number, a String representation of an Object and a boolean.

StringBuilder append(char[] cstr, int set, int length)

Let’s look at the append() method with three parameters. It adds a representation of a subarray of a given char array to the string. So here:
  • cstr is an array of characters to be appended
  • set it the index of the first character to be append
  • length is the quantity of characters to append.
Similarly to other append() methods, this one returns an expanded StringBuilder object. Here’s an example of using append(char[], cstr, int set, int length) as a part of Java app code.
public class AppendDemo {
   // an example of using append(char[], cStr, int set, int length)

   public static void main(String[] args) {
       StringBuilder s = new StringBuilder("I love ");
      //here is a char's array, part of which we are going to append to s
       char[] cStr = new char[]
               {'c', 'o', 'd', 'e', 'J', 'a', 'v', 'a', '1', '4'};
       //we append 4 elements of cStr from the 4th element "J"
       s.append(cStr, 4, 4);
       System.out.println(s);
   }
}
The output is:
I love Java

StringBuilder append() methods with CharSequence argument

You may have noticed two methods that have CharSequence as their arguments.
  • public StringBuilder append(CharSequence cs)
  • public StringBuilder append(CharSequence cs, int start, int end)
Not all beginners know that CharSequence is an Interface. According to documentation CharSequence is a readable sequence of char values and provides uniform, read-only access to many different kinds of char sequences.The interface is implemented by such Java Classes as String, StringBuffer, StringBuilder and more. So if you don’t know what is better to use in your program, String, StringBuffer or StringBuilder you can use CharSequence. StringBuilder append(CharSequence cs, int start, int end) works almost as append(char[] cstr, int set, int length) we discussed above. However, this method specifies the first element of the subsequence and the last. It is important to remember that start is included in the subsequence, but end is not (that is, the last element in the subsequence is the element that comes before end). Why is that? It's just the way it is in Java. Let’s demonstrate what CharSequence is and append(CharSequence cs) and append(CharSequence cs, int start, int end) methods.
public class CharSequenceDemo {

   public static void printCharSequence(CharSequence ch) {
       System.out.println(ch);
   }
       public static void main(String[] args) {
           CharSequence myString = new String("This is String ");
           printCharSequence(myString);
           CharSequence myStringBuilder = new StringBuilder("This is StringBuilder ");
           printCharSequence(myStringBuilder);
           StringBuilder s = new StringBuilder("my StringBuilder ");
//StringBuilder.append
s.append(myStringBuilder);
           System.out.println(s);
//StringBuilder.append
           s.append(myString);
           System.out.println(s);
           s.append(myString, 5,7);
           System.out.println(s);
       }
   }
The output is:
This is String This is StringBuilder my StringBuilder This is StringBuilder my StringBuilder This is StringBuilder This is String my StringBuilder This is StringBuilder This is String is
We created two CharSequences, bound String and StringBuilder to them and printed them out. We cannot apply the append() method directly to myStringBuilder, since CharSequence does not have this method (if you don’t understand why, you need to figure out about inheritance as well as expanding and narrowing of reference types). Therefore, we create a StringBuilder with and concatenate using the append method sequentially with both CharSequence. At the end we appended our StringBuilder with subsequence “is” (“i” is a 5th element of myStringBuilder and s is the 6th. Remember that in the method, the element specified as end is excluded from the subsequence.

What about StringBuffer append()?

StringBuffer.append also has 13 variants of the method and they work exactly the same way as StringBuilder.
  • public StringBuffer append​(boolean b)
  • public StringBuffer append​(char c)
  • public StringBuffer append​(char[] str)
  • public StringBuffer append​(char[] str, int offset, int len)
  • public StringBuffer append​(double d)
  • public StringBuffer append​(float f)
  • public StringBuffer append​(int i)
  • public StringBuffer append​(long lng)
  • public StringBuffer append​(CharSequence s)
  • public StringBuffer append​(CharSequence s, int start, int end)
  • public StringBuffer append​(Object obj)
  • public StringBuffer append​(String str)
  • public StringBuffer append​(StringBuffer sb)
Let's have an example of StringBuffer.append to join a substring. We just take the StringBuilder example and change all StringBuilders in code to StringBuffers.
public class AppendDemo {
   // an example of using append(char[], cStr, int set, int length)

   public static void main(String[] args) {
       StringBuffer s = new StringBuffer("I love ");
      //here is a char's array, part of which we are going to append to s
       char[] cStr = new char[]
               {'c', 'o', 'd', 'e', 'J', 'a', 'v', 'a', '1', '4'};
       //we append 4 elements of cStr from the 4th element "J"
//with StringBuffer.append
       s.append(cStr, 4, 4);
       System.out.println(s);
//StringBuffer.append adds int 14 to s
s.append(14);
System.out.println(s);
   }
}
The output is:
I love Java I love Java14
You can do it with every example of this article. They will work!

Conclusion

Since StringBuilder and StringBuffer share most functions, it’s no surprise that both classes have similar ways to use the append() method. That’s good news for developers — you don’t have to learn separate methods for each class. Having said that, considering the variety of ways to use append(), make sure to put in a few hours of practice adding the representations of different data types to a string.
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet