Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuffer vs StringBuilder Vs StringTokenizer

Tags:

java

what is the difference between the StringBuffer vs StringBuilder Vs StringTokenizer on the internal implementation. when to use these . kindly waiting for the answer.

Update:-

I am also going through the source code.

like image 269
Dead Programmer Avatar asked Sep 24 '10 09:09

Dead Programmer


People also ask

Which is better StringBuilder or StringBuffer?

String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer.

What is a StringTokenizer?

The string tokenizer class allows an application to break a string into tokens. The tokenization method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer methods do not distinguish among identifiers, numbers, and quoted strings, nor do they recognize and skip comments.

What is the StringTokenizer example?

Example of StringTokenizer Class Let's see an example of the StringTokenizer class that tokenizes a string "my name is khan" on the basis of whitespace. The above Java code, demonstrates the use of StringTokenizer class and its methods hasMoreTokens() and nextToken().

Why StringBuffer is slower than StringBuilder?

Because StringBuffer methods are synchronized whereas StringBuilder methods are not, there is a speed difference. StringBuffer is more secure to use than StringBuilder, but it is also slower due to the additional synchronization mechanisms.


2 Answers

StringBuffer - introduced in JDK 1.0 - is thread safe (all of its methods are synchronized), while StringBuilder - since JDK 1.5 - is not. Thus it is recommended to use the latter under normal circumstances.

StringTokenizer is meant for a whole different purpose then the former two: cutting strings into pieces, rather than assembling. As @Henning noted, it is also "retired" since JDK 1.5 - it is recommended to use String.split instead.

like image 148
Péter Török Avatar answered Oct 11 '22 15:10

Péter Török


  • StringBuffer is designed to be thread-safe and all public methods in StringBuffer are synchronized. StringBuilder does not handle thread-safety issue and none of its methods is synchronized.

  • StringBuilder has better performance than StringBuffer under most circumstances.

  • Use the new StringBuilder wherever possible.

Here is performance comparison of StringBuilder & StringBuffer

StringBuilder & StringBuffer Holds String where StringoTokeizer class allows an application to break a string into tokens .. So It is like odd one out

like image 38
jmj Avatar answered Oct 11 '22 14:10

jmj