- Previous
- Next
In this article, we will create a program that uses both String-Builder and String-Buffer Class and displays the output. The main difference between these two class is that String-Builder Class is not threading safe like String-Buffer Class.
String-Buffer class objects are like String objects, but it can be modified at any time because it contains a sequence of characters.
This program is a basic introduction to the string-buffer and string-builder class. It is intended for beginner level learner of Java programming language.
Problem Definition
String-Buffer objects can be used with multiple threads. There are two important operations performed on String-Buffer class objects.
1. Append
2. Insert
String-Builder is like a replacement for String-buffer class instance. It also performs the same operation on data inputs. To create a program in Java that makes use of both String-Builder and String-Buffer Class use the following code.
Program Code
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package JavaExamples;
/**
*
* @author Admin
*/
public class StringBufferDemo {
public static void main(String[] args)
{
String s;
String p;
StringBuilder sb = new StringBuilder(40);
StringBuffer sp = new StringBuffer(40);
int b = 40;
int a = 50;
s = sb.append("a = ").append(a).append("!").toString();
p = sp.append("b = ").append(b).append("!").toString();
System.out.println(s);
System.out.println(s.length());
System.out.println(p);
System.out.println(p.length());
}
}
Output
Output of the above program is given below.
a = 50!
7
b = 40!
7