How to take input for a StringBuffer Object In Java?

For example, we can accept an object of String class as input in the below codes. How do you do the same for a StringBuffer class?

String a = new String();
Scanner in = new Scanner(;
System.out.println("Enter a String");


The code:

StringBuffer sbuffer = new StringBuffer();
Scanner input = new Scanner(;
System.out.println("Enter a string");

will add your ‘next line’ to the StringBuffer sbuffer.

This is because input.nextLine() returns a String, and sbuffer.append(...) accepts a variety of arguments, including Strings.

The documentation for a StringBuffer can be found at this Java page.

Likewise, scanner documentation is also available.

These links provide a list of the methods available for each of these classes, along with the arguments/parameters that methods can take. The Java documentation frequently gives examples of use cases.

From the opening paragraph of the StringBuffer documentation:

A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls.

String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

Leave a Reply

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