Java from the basic Knowledge (ii) string processing

Source: Internet
Author: User

Strings are most frequently used in program development, so it is particularly important to understand and master the processing of strings in order to work efficiently and as a programmer who wants to be advanced. Java provides us with string, StringBuffer, Stringbuilde Three processing strings of the class, the following we do a summary and introduction.

1, respectively introduced

1) String

Answer 1:

When we look at the API documentation, we find that the phrase "strings are constants and their values cannot be changed after they are created." It is well known that constants are final decorated and cannot be modified when created elsewhere in the program. At this point we will quickly recall that in our daily development, the string can be assigned anywhere and anytime, is the JDK API documentation is wrong? In fact, below we explain the principle.

public static void Main (String arg[]) {
String str1 = "a";
String str2 = str1;
String STR4 = str2;
System.out.println (str1 = = str2);//true, description reference stt1 and reference str2 point to the same address
String STR3 = "B";
STR1 = str1 + str3;
System.out.println (str1 = = str2);//false, indicating that the address pointed to by the reference str1 has changed
System.out.println (str2 = = STR4);//true
str2 = str2 + str3;
System.out.println (str2 = = STR4);//false, indicating that the address pointed to by the reference str2 has changed
System.out.println (str1 = = str2);//false
}

Because string is a reference type, the reference type is stored in memory as

  

That is, when we make a change to str1, we simply change the address to which the reference stored in the stack memory is pointing, while the Java virtual Opportunity allocates new space for it in the heap memory, and the original heap memory address stores the value (because it is a constant) and does not change. will be treated as useless references by the Java Recycle Bin, which is believed to be a smooth understanding of the above code.

Answer 2:

public class Test {

Private final static String S1 = "abc";
Private final static String s2 = "abc";

public static void Main (String arg[]) {
String str1= "ABC";
String str2= "ABC";
String str3= "AB" + "C";
String Str4=new string (STR2);
System.out.println (str1 = = str2);//true, stating str1, str2 point to the same address
System.out.println (str1 = = STR3);//true, stating str1, Str3 point to the same address
System.out.println (str1 = = STR4);//false, stating str1, STR4 pointing to different addresses
System.out.println (S1 = = s2);//true, stating S1, S2 point to the same address
System.out.println (str1 = = S1);//true, stating str1, S1 point to the same address
}

}

The above phenomenon is determined by the storage rules in memory, where Java code allocates a chunk of storage in the heap as a constant pool for storing constant values in the compilation phase. When a constant is declared, the compiler will go to the constant pool to find out if the string exists, and if it does, point the string's reference directly to the address of the string, otherwise allocate a new space in the constant pool, meaning that references to constants of the same value will point to the same storage address. As for STR4, the compiler has new storage space for it, which is treated as an object, not as a constant.

The following is an in-memory storage allocation for constants

  

Common ways to answer 3:string

  equals (object AnObject) and equalsignorecase(String anotherstring): Equals is a very frequent method used in development and requires distinguishing between equals and "= =" objects, equals compares the values of two objects (references) for equality, the objects that are compared by "= =" can be either basic data types or reference types, when the comparison object is the base data type is the comparison of the value, when comparing the object is a reference type when comparing the reference (referring to the address), Instead of the value pointed to by the reference. The latter is a case-insensitive comparison.

  contentequals (Charsequence CS),contentequals(StringBuffer SB): String compared to the specified charsequence/stringbuffer.

  compareTo(String anotherString)and compareToIgnoreCase(String str) : Compares two strings in a dictionary order, which ignores case.

matches (String regex): whether the current string matches the given regular expression.

length (): Returns the length of the secondary string

  IsEmpty (): Returns True when and only if it length() is 0 .

Split (String regex) split(String regex, int limit) : Splits a string according to the given regular expression

  substring(int beginIndex),substring(int beginindex, int endIndex): Returns substrings of this string by rule

  Replace (Char OldChar, char Newchar),replace(charsequence target, charsequence replacement),ReplaceAll( String regex, String replacement): Replace

  valueOf (Boolean B), etc.: Returns the string representation of the base data type

  valueOf (Object obj): Returns the string form of an object

  toLowerCase () and touppercase(): Converts all characters in this string to lowercase/uppercase using the default locale

  ToCharArray (): Convert string to character array

  contains(CharSequence s): Returns True when and only if the string contains a sequence of specified char values.

  indexOf(int ch),,, indexOf(int ch, int fromIndex) indexOf(String str) indexOf(String str, int fromIndex) : Returns the index by rule.

  lastIndexOf(int ch),lastIndexOf(int ch, int fromIndex),lastIndexOf(String str),lastIndexOf(string str, int FromIndex): Returns the index of the last occurrence of the specified character or string by rule.

  concat (String str): Specifies that the string is concatenated to the end of this string. (General with the + number solved, so with very little)

2) StringBuffer

A variable sequence of characters for thread safety.

  Append (String str), etc.: appends a string to this string

  Insert (int offset, string str), etc.: inserting a string into this sequence of characters

  Reverse (): Replaces this sequence of characters with its inverted form. This is a very useful way to easily reverse the specified string output.

  toString (): Convert StringBuffer string to string

3) Stringbuilde

A variable sequence of characters, basic and StringBuffer, but non-thread-safe, so efficiency is higher than StringBuffer, Stringj.

2, String, Stringbuilde, stringbuffer comparison

1, Stringbuilde is non-thread-safe, StringBuffer is thread-safe.

2, efficiency on String<stringbuffer<stringbuilde

This is because string is a string constant, and the other two are string variables, and each time the string is assigned a new object (described in detail above), the original object will be garbage collected by GC, which will greatly reduce the efficiency of execution. While StringBuffer and StringBuilder are string variables, the change takes place in the same object, with less creation and destruction of the object link.

Finally, if the operation of a small amount of data using a string, if the single-threaded operation of large amounts of data is StringBuilder, if the multi-threaded operation of large amounts of data is used StringBuffer.

Java from the basic Knowledge (ii) string processing

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.