Differences in string, StringBuffer, StringBuilder, StringTokenizer in Java

Source: Internet
Author: User
Tags stringtokenizer in java

In the Java language, there are 4 classes that can manipulate characters or strings, which are character, string, StringBuffer, StringTokenizer, where character is used for a single character operation, string for string manipulation, is an immutable class, and StringBuffer is also used for string manipulation, but the difference is that StringBuffer belongs to a mutable class.

A string is an immutable class, that is, when a string object is created, its value cannot be changed, and StringBuffer is a mutable class, and its value can still be modified when the object is created. Because string is immutable, it is suitable for use in situations where it needs to be shared, and it is best to use StringBuffer when a string is often required to be modified. If you use string to hold a string that is often modified, the string is modified with a lot more additional operations than StringBuffer, and many useless objects are generated, because these useless objects are recycled by the garbage collector, which can affect the performance of the program.

  1. Package test;
  2. Public class test{
  3. public static void TestString () {
  4. String s="Hello";
  5. String s1="World";
  6. long Start=system.currenttimemillis ();
  7. For (int i=0;i<10000;i++) {
  8. S+=S1;
  9. }
  10. long End=system.currenttimemillis ();
  11. long Runtime= (End-start);
  12. System.out.println (RunTime);
  13. }
  14. public static void Teststringbuffer () {
  15. StringBuffer s=New StringBuffer ("Hello");
  16. String s1="World";
  17. long Start=system.currenttimemillis ();
  18. For (int i=0;i<10000;i++) {
  19. S.append (S1);
  20. }
  21. long End=system.currenttimemillis ();
  22. long Runtime= (End-start);
  23. System.out.println (RunTime);
  24. }
  25. public static void Teststringbuilder () {
  26. StringBuilder s=New StringBuilder ("Hello");
  27. String s1="World";
  28. long Start=system.currenttimemillis ();
  29. For (int i=0;i<10000;i++) {
  30. S.append (S1);
  31. }
  32. long End=system.currenttimemillis ();
  33. long Runtime= (End-start);
  34. System.out.println (RunTime);
  35. }
  36. public static void Main (string[] args) {
  37. TestString ();
  38. Teststringbuffer ();
  39. Teststringbuilder ();
  40. }
  41. }

The result of the program operation is:

265
16
0

From the running results, when a string is often modified, using StringBuffer is much better than using string.

StringBuilder can also be decorated with strings, which are similar to StringBuffer, are string buffers, but StringBuilder is not thread-safe, and if only a single thread uses a string buffer, Then the efficiency of the StringBuilder will be higher. StringBuilder can therefore be used when there is only single-threaded access, and it is best to use thread-safe stringbuffer when there are multiple off-the-shelf access. Because StringBuffer can synchronize these methods when necessary, all operations on any particular instance appear to occur in a serial order that is consistent with the order in which the method calls are made by each thread involved.

In terms of execution efficiency, StringBuilder is the highest, stringbuffer second, and string is the lowest.

StringTokenizer is a tool class for splitting strings, as shown in the following example:

1). constructor.

1. StringTokenizer (String str): Constructs a StringTokenizer object to parse str. The default Java delimiter is "space", "tab (' \ t ')", "line feed (' \ n ')", "carriage return (' \ R ')". 2. StringTokenizer (String str, string Delim): Constructs a StringTokenizer object to parse STR and provides a specified delimiter. 3. StringTokenizer (String str, String Delim, Boolean returndelims): Constructs a StringTokenizer object to parse str, and provides a specified delimiter, at the same time, Specifies whether to return delimiters.

2). Introduction to Methods

int Counttokens (): Returns the number of times the Nexttoken method was called. If constructors 1 and 2 are used, the number of separators is returned
Boolean hasmoreelements (): Returns whether there is a delimiter.
Boolean Hasmoretokens (): Ibid.
String NextToken (): Returns the string from the current position to the next delimiter.
Object Nextelement (): Same as the result, unless life returns an object instead of a string
String NextToken (String delim): Same as NextToken (), returns the result with the specified delimiter

Cases:

string s = new String ("This is a test string"); StringTokenizer st = new StringTokenizer (s); System.out.println ("Token total:" + st.counttokens ()), while (St.hasmoreelements ()) {    System.out.println ( St.nexttoken ());}

Example 2:

String str = "100|66,55:200|567,90:102|43,54"; StringTokenizer Strtoke = new StringTokenizer (str, ":, |"); /default does not print delimiter//StringTokenizer strtoke=new StringTokenizer (str, ":, |", true);//print delimiter//StringTokenizer strtoke=new StringTokenizer (str, ":, |", false);//do not print delimiter while (Strtoke.hasmoretokens ()) {    System.out.println ( Strtoke.nexttoken ());}

Note that the StringTokenizer delimiter does not need to use escape characters

3). The difference from split

String.Split () uses regular expressions, while StringTokenizer only uses characters that are split verbatim.
If you do not use a regular expression (StringTokenizer also does not work with regular expressions), StringTokenizer is the most efficient in intercepting strings.

Differences in string, StringBuffer, StringBuilder, StringTokenizer in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.