Java String, StringBuffer, and StringBuilder instances

Source: Internet
Author: User
Tags first string locale stringbuffer vs stringbuilder


1-Hierarchical inheritance
2-Variable and immutable concepts
3-string
3.1-string is a very special class
3.2-string literals vs. String objects
Methods of 3.3-string
3.3.1-length ()
3.3.2-concat (String)
3.3.3-indexof (..)
3.3.4-substring (..)
3.3.5-replace
3.3.6-Other Instances
4-stringbuffer vs stringbuilder1-Hierarchical inheritance
When working with text data, Java provides three categories, including String, StringBuffer, and StringBuilder. When working with big data, you should use StringBuffer or StringBuilder to optimize efficiency. There are basically a lot of similarities between these three classes.
    • The String is immutable (more detailed information about this concept in the document). It does not allow the existence of subclasses.
    • StringBuffer, StringBuilder is mutable.
StringBuilder and StringBuffer are the same, except for the use of multithreading.
    • In order to handle multithreaded use of text, you should use StringBuffer to prevent conflicts between threads.
    • To use text that is processed by a thread, you should use StringBuilder.

As for the speed of processing, StringBuilder is the best, followed by the StringBuffer, and finally the string. 2-Variable and immutable concepts consider one of the following examples

// This is a class with value field and name field.
// When you create this class, you cannot reset the value and all other fields from outside.
// This class does not have methods for the purpose of resetting fields from outside.
// It means this class is immutable
public class ImmutableClassExample {
   private int value;
   private String name;

   public ImmutableClassExample (String name, int value) {
          this.value = value;
          this.name = name;
   }

   public String getName () {
          return name;
   }

   public int getValue () {
         return value;
   }
}


// This is a class owning a value field.
// After creating the object, you can reset values of the value field by calling setNewValue (int) method.
// This is a mutable class.
public class MutableClassExample {

     private int value;

     public MutableClassExample (int value) {
           this.value = value;
     }

     public void setNewValue (int newValue) {
          this.value = newValue;
     }

}
String is an immutable class. String includes various fields such as length, but the values in these fields cannot be changed. 3- String String is the most important class in Java. When Java programming starts with strings, it uses the famous System.out.println () statement to print things on the console. Many Java beginners do not know that String is immutable and the final Java string result, each modification needs to create a new String object. 3.1- String is a very special class. Strings receive special processing from Java because they are often used in programs. Therefore, efficiency (in terms of computing and storage) is crucial. The designers of Java decided on this object-oriented language to preserve the primitive types instead of making all objects in order to improve the performance of the language. The original data is stored (on) the call stack, which requires less storage space and more convenient operation. On the other hand, objects are stored in the program heap, which requires complex memory management and more storage space. For performance reasons, Java strings are designed to be between a primitive and a class. Special function strings include:
The "+" operator, which performs additions to primitive types (such as int and double), overloads on String objects ‘+’ Two string operands are concatenated. Java does not consider allowing developers to support operator overloading. In supporting operator overloading like C ++ language, you can put a "+" operator to perform subtraction, causing bad code. The "+" operator is the only operator in Java that supports overloaded internal string concatenation. Note that "+" does not work on two arbitrary objects.
A string can be constructed by:
Directly assign a string to a string reference-just like a primitive data type or through the "new" operator and construct, similar to any other class. However, this is not commonly used, so it is not recommended.
Strings are stored literally in a common pool. This is beneficial for sharing strings with the same content to save storage. The String objects allocated by the new operator are stored in the heap, and there is no shared storage for the same content.
E.g:
// Implicit construction via string literal
String str1 = "Java is Hot";

// Explicit construction via new
String str2 = new String ("I ‘m cool");
 
3.2- String literals and String objects As mentioned earlier, there are two ways to construct a string: by specifying a string literal or explicitly creating it through the new operator, and constructing an implicit construction of a String object. E.g,
String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String ("Hello"); // String object
String s5 = new String ("Hello"); // String object
We explain it with a piece of instructions:
Java has provided a special mechanism to save string literals-the so-called string public pool. If two strings have the same content, they will share the same storage in the common pool. Such an approach is taken to save the storage of frequently used strings. On the other hand, String objects created by the new operator and constructor are stored in the heap. Each String object in the heap has its own storage just like any other object. There is no shared storage heap, even if two String objects have the same content. You can use the equals () method of the String class to compare the contents of two strings. You can use the relational equality operator ‘==’ to compare references (or pointers) of two objects. Study the following code:
String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String ("Hello"); // String object
String s5 = new String ("Hello"); // String object

s1 == s1; // true, same pointer
s1 == s2; // true, s1 and s2 share storage in common pool
s1 == s3; // true, s3 is assigned same pointer as s1
s1 == s4; // false, different pointers
s4 == s5; // false, different pointers in heap

s1.equals (s3); // true, same contents
s1.equals (s4); // true, same contents
s4.equals (s5); // true, same contents
In fact, you should use strings instead of using the "new" operator, which helps speed up the program. 3.3- String method The following is a string list method:
SN method description
1 char charAt (int index) returns the character at the specified index
2 int compareTo (Object o) compares another object of the string
3 int compareTo (String anotherString) lexicographically compare two strings
4 int compareToIgnoreCase (String str) Compare two strings in lexicographical order, ignoring case differences
5 String concat (String str) Add the specified string to the end of the string
6 boolean contentEquals (StringBuffer sb) Returns true if and only if this String indicates that the characters are in the same order as the specified StringBuffer
7 static String copyValueOf (char [] data) returns a string representing the sequence of characters in the specified array
8 static String copyValueOf (char [] data, int offset, int count) returns a string representing the sequence of characters in the specified array
9 boolean endsWith (String suffix) Test whether this string ends with the specified suffix
10 boolean equals (Object anObject) compares the object specified by this string
11 boolean equalsIgnoreCase (String anotherString) This string is compared with another string, regardless of case
12 byte getBytes () Decode this String using the platform's default character set byte sequence, and store the result to a new byte array
13 byte [] getBytes (String charsetName) Decode this String using the specified character set byte sequence and store the result in a new byte array
14 void getChars (int srcBegin, int srcEnd, char [] dst, int dstBegin) copy the characters of this string to the target character array
15 int hashCode () returns the hash code of this string
16 int indexOf (int ch) returns the index of the first occurrence of the specified character in this string
17 int indexOf (int ch, int fromIndex) Returns the index of the specified character in this string, the first occurrence from the search of the specified index
18 int indexOf (String str) returns the index of the first occurrence of the specified child of this string
19 int indexOf (String str, int fromIndex) Returns the index of the first occurrence of the specified substring of this string from the specified index
20 String intern () returns the canonical representation of the string object
21 int lastIndexOf (int ch) Returns the index of the last occurrence of the specified character in this string
22 int lastIndexOf (int ch, int fromIndex) Returns the index of the last occurrence of the specified character in this string, searching backward from the specified index
23 int lastIndexOf (String str) Returns the index at the rightmost occurrence of the specified sub of this string
24 int lastIndexOf (String str, int fromIndex) Returns the index of the last occurrence of the specified child of this string, starting search backward at the specified index
25 int length () returns the length of this string
26 boolean matches (String regex) Determines whether this string matches the given regular expression.
27 boolean regionMatches (boolean ignoreCase, int toffset, String other, int ooffset, int len)
Check if two string regions are equal
28 boolean regionMatches (int toffset, String other, int ooffset, int len) Check whether two string regions are equal
29 String replace (char oldChar, char newChar) returns from this string 
Use newChar to replace all occurrences of oldChar in the string
30 String replaceAll (String regex, String replacement) This replacement string uses the given regular expression to match and replace each substring
31 String replaceFirst (String regex, String replacement) This replacement string uses the given regular expression to match and replace the first string
32 String [] split (String regex) Split this string around the matching of the given regular expression
33 String [] split (String regex, int limit) Split this string around the matching of the given regular expression
34 boolean startsWith (String prefix) Test whether this string starts with the specified prefix
35 boolean startsWith (String prefix, int toffset) Check whether this string starts from the specified index and starts with the specified prefix
36 CharSequence subSequence (int beginIndex, int endIndex) returns a new character sequence which is a subsequence of this sequence
37 String substring (int beginIndex) returns a new string which is a substring of this string
38 String substring (int beginIndex, int endIndex) returns a new string which is a substring of this string
39 char [] toCharArray ()
 Convert this string to a new character array
40 String toLowerCase ()
 Convert all the characters in this string to the default locale rules to lower case
41 String toLowerCase (Locale locale)
 Convert all characters in this string to lower case using the rules of the given Locale
42 String toString () This object (which is already a string!) Returns itself.
43 String toUpperCase () All characters in this string are converted to uppercase using the rules of the default locale.
44 String toUpperCase (Locale locale) All characters in this string are converted to uppercase using the given Locale rules
45 String trim () returns a copy of the string, with blanks at the beginning and end
46 static String valueOf (primitive data type x) Returns the string representation of the passed data type parameter 3.3.1- length ()
LengthDemo.java
package com.yiibai.tutorial.str;

public class LengthDemo {

    public static void main (String [] args) {
        String str = "This is text";
        int len = str.length ();
        System.out.println ("String Length is:" + len);
    }
}
Results of running the example:
3.3.2- concat (String)
ConcatDemo.java
package com.yiibai.tutorial.str;

public class ConcatDemo {

    public static void main (String [] args) {
        String s1 = "One";
        String s2 = "Two";
        String s3 = "Three";

        // s1.concat (s2) same as s1 + s2
        String s = s1.concat (s2);
        System.out.println ("s1.concat (s2) =" + s);

        // s1.concat (s2) .concat (s3) same as s1 + s2 + s3;
        s = s1.concat (s2) .concat (s3);

        System.out.println ("s1.concat (s2) .concat (s3) =" + s);
    }
}
Results of running the example:
s1.concat (s2) = OneTwo
s1.concat (s2) .concat (s3) = OneTwoThree
3.3.3- indexOf (..)
IndexOfDemo.java
package com.yiibai.tutorial.str;

public class IndexOfDemo {

    public static void main (String [] args) {
        String str = "This is text";
       
        // Find index within this string of the first occurrence ‘i’.
        // ==> 2
        int idx = str.indexOf (‘i‘);
        System.out.println ("-indexOf (‘ i ‘) =" + idx);

      
        // Find index within this string of the first occurrence ‘i’
        // starting the search at index 4.
        // ==> 5
        idx = str.indexOf (‘i‘, 4);
        System.out.println ("-indexOf (‘ i ‘, 4) =" + idx);
       
        // index within this string of the first occurrence of "te".
        // ==> 8
        idx = str.indexOf ("te");
        System.out.println ("-indexOf (‘ te ‘) =" + idx);
    }

}
Results of running the example:
-indexOf (‘i‘) = 2
-indexOf (‘i‘, 4) = 5
-indexOf (‘te‘) = 8
3.3.4- substring (..)
SubstringDemo.java
package com.yiibai.tutorial.str;

public class SubstringDemo {

    public static void main (String [] args) {
        String str = "This is text";

        // Returns the substring from index 3 to the end of string.
        String substr = str.substring (3);

        System.out.println ("-substring (3) =" + substr);

        // Returns the substring from index 2 to index 7.
        substr = str.substring (2, 7);

        System.out.println ("-substring (2, 7) =" + substr);
    }
}
Results of running the example:
-substring (3) = s is text
-substring (2, 7) = is is
3.3.5- replace and replace some methods.
// Returns a new string resulting from replacing all occurrences of
// oldChar in this string with newChar.
public String replace (char oldChar, char newChar)

// Replaces each substring of this string that matches the given
// ‘regular expression’ with the given replacement.
public String replaceAll (String regex, String replacement)

// Replaces the first substring of this string that matches
// the given <‘regular expression‘ with the given replacement.
public String replaceFirst (String regex, String replacement)
ReplaceDemo.java
package com.yiibai.tutorial.str;

public class ReplaceDemo {

    public static void main (String [] args) {
        String str = "This is text";

        // Replace the character ‘i‘ by ‘x’.
        String s2 = str.replace (‘i‘, ‘x’);

        System.out.println ("-s2 =" + s2);

        // Replace all the strings match "is" by "abc". (Regular Expression)
        String s3 = str.replaceAll ("is", "abc");

        System.out.println ("-s3 =" + s3);

        // Replaces the first substring of this string that matches "is" by "abc".
        String s4 = str.replaceFirst ("is", "abc");

        System.out.println ("-s4 =" + s4);
       
        // (See also document the regular expression)
        // Replace all substring matching expression:
        // "is | te": means "is" or "te" replaced by "+".
        String s5 = str.replaceAll ("is | te", "+");
        System.out.println ("-s5 =" + s5);
    }

}
Results of running the example:
-s2 = Thxs xs text
-s3 = Thabc abc text
-s4 = Thabc is text
-s5 = Th + + + xt
3.3.6- Other examples
StringOtherDemo.java
package com.yiibai.tutorial.str;
public class StringOtherDemo {

    public static void main (String [] args) {
        String str = "This is text";

        System.out.println ("-str =" + str);

        // Return lower case string.
        String s2 = str.toLowerCase ();

        System.out.println ("-s2 =" + s2);

        // Return upper case string
        String s3 = str.toUpperCase ();

        System.out.println ("-s3 =" + s3);

        // Check string started by "This" or not.
        boolean swith = str.startsWith ("This");

        System.out.println ("-‘ str ‘startsWith This?" + Swith);
       
        // A string with whitespace in beginning and end.
        // Note: \ t is tab character
        // \ n is new line character
        str = "\ t Java is hot! \ t \ n";

        System.out.println ("-str =" + str);

        // Returns a copy of the string, with leading and trailing whitespace omitted.
        String s4 = str.trim ();

        System.out.println ("-s4 =" + s4);
    }

}
Results of running the example:
-str = This is text
-s2 = this is text
-s3 = THIS IS TEXT
-‘Str’ startsWith This? True
-str = Java is hot!
 
-s4 = Java is hot!
4- StringBuffer vs StringBuilder
StringBuffer is variable. It can change in length and content. StringBuffers are thread safe, which means they have synchronized methods to control access so that only one thread can access a StringBuffer object synchronization code at the same time. Therefore, StringBuffer objects are usually safe in a multi-threaded environment, using multiple threads can try to access the same StringBuffer object at the same time.

The StringBuilder class is very similar to StringBuffer, the difference is that its access is not synchronized, therefore, it is not thread safe. Due to the lack of synchronization, the performance of StringBuilder can be better than StringBuffer. Therefore, if you work in a single-threaded environment, using StringBuilder instead of StringBuffer may have higher performance. This is similar to other situations, such as StringBuilder local variables (that is, a variable in a method), where only one thread will access a StringBuilder object.

StringBuffer method (similar to StringBuilder)
// Constructors
StringBuffer () // an initially-empty StringBuffer
StringBuffer (int size) // with the specified initial size
StringBuffer (String s) // with the specified initial content

// Length
int length ()

// Methods for building up the content
// type could be primitives, char [], String, StringBuffer, etc
StringBuffer append (type arg) // ==> note above!
StringBuffer insert (int offset, type arg) // ==> note above!

// Methods for manipulating the content
StringBuffer delete (int start, int end)
StringBuffer deleteCharAt (int index)
void setLength (int newSize)
void setCharAt (int index, char newChar)
StringBuffer replace (int start, int end, String s)
StringBuffer reverse ()

// Methods for extracting whole / part of the content
char charAt (int index)
String substring (int start)
String substring (int start, int end)
String toString ()

// Methods for searching
int indexOf (String searchKey)
int indexOf (String searchKey, int fromIndex)
int lastIndexOf (String searchKey)
int lastIndexOf (String searchKey, int fromIndex)
StringBuilderDemo.java
package com.yiibai.tutorial.strbb;


public class StringBuilderDemo {

    public static void main (String [] args) {
       
        // Create StringBuilder object
        // with no characters in it and
        // an initial capacity specified by the capacity argument
        StringBuilder sb = new StringBuilder (10);
        
        // Append the string Hello ... on sb.
        sb.append ("Hello ...");
        System.out.println ("-sb after appends a string:" + sb);

        // append a character
        char c = ‘!’;
        sb.append (c);
        System.out.println ("-sb after appending a char:" + sb);

        // Insert a string at index 5
        sb.insert (8, "Java");
        System.out.println ("-sb after insert string:" + sb);
        
    
        // Delete substring at index 5 to 8
        sb.delete (5,8);

        System.out.println ("-sb after delete:" + sb);
    }
}
Results of running the example:
-sb after appends a string: Hello ...
-sb after appending a char: Hello ...!
-sb after insert string: Hello ... Java!
-sb after delete: Hello Java!
 

 
Java String, StringBuffer and StringBuilder examples

Related Article

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.