Java base String operation — String

string

What is a string? A sequence of concatenated characters. To better understand the above theory, let’s first explain character sequences, character sequences: multiple characters arranged in a certain order; Character sequences exist as the contents of strings. Therefore, a string can be understood as a combination of multiple characters arranged in a certain order.

If it’s still hard to understand, it doesn’t matter. I have a secret. Think of a string as a kebab, where each piece of meat on the kebab is equivalent to a character. In the same way that pieces of meat are arranged in the order of fat and thin and strung together to form a kebab, strings of characters are “strung” together in a certain order.

The classification of strings is divided into variable strings and immutable strings. Immutable and mutable here refer to whether the object of the string is the same or not, and whether new objects will be created because the contents of the string object change.

  • An immutable stringWhen a string object is created, its contents cannot be changed. Once the contents are changed, a new string object is created.JavaIn theStringClass objects are immutable.
  • Mutable string:StringBuilderClasses andStringBufferClass objects are mutable; After an object is created, no new object is created when the contents of the object change. That is, the contents of the object can be changed. When the contents of the object change, the object remains unchanged and remains the same.

The String class

The String class represents an immutable String. After the current String object is created, the contents of the object (the sequence of characters) are immutable, because new objects are created once the contents are changed.

String creation:

  1. Method 1: create by literal assignment,String s1 = "laofu";Note that there are double quotes:"", which differs from the character char type in single quotes:' ';
  2. Method two: create from the constructor,String s2 = new String("laofu");;

How are objects created in these two ways distributed within the JVM? What’s the difference?

How are modes one and two distributed within the JVM?

Constant pool in the figure above: the local memory area for storing constants, located in the method area. Constant pools are divided into compiled constant pools and running constant pools:

  • Compile constant pool: when loading bytecode intoJVM, which stores the bytecode related information (such as the line number of the bytecode currently executed).
  • Run constant pools: Where constant data is stored in code.

What’s the difference between method one and method two?

  • String s1 = “laofu”; You may create only a String, or you may create no String at all; If “laofu” already exists in the constant pool, s1 will reference it directly and will not create a new String. Otherwise, memory space for the constant “laofu” is created in the constant pool first, and then referenced.

  • S2 = new String(“laofu”); At most two strings are created and at least one String is created. The object that can be created using the new keyword creates a memory region in the heap space, which is the first object; Then the String literal in the object may create a second object, and the second object may not be created as described in method 1, so create at least one String object.

Char [] is a character, for example:

String str = "laofu"; Char [] cs = new char[]{'l'.'a'.'o'.'f'.'u'};
Copy the code

Null value of String:

  1. Object reference is null, that is:String s1 = null;At this times1There’s no initialization, there’s alsoJVMNo memory space is allocated in.
  2. The object contains an empty string, such as:String s2 = "";The object s2 has been initialized with a value of"".JVMMemory space has been allocated for it.

** String comparison: ** Using “==” and “equals” has different effects. Static does not allow static

  1. use= =Number: used to compare whether the memory addresses of object references are the same.
  2. useequalsMethods:ObjectThe class and= =The numbers are the same, but in custom classes, overrides are recommendedequalsMethod to compare the details of your content; Due to theStringClass coverage is already coveredequalsMethod, so it compares character content.

So we can tell if the string is not empty:

  1. Object references cannot be null:s1 ! = null;;
  2. Character content cannot be an empty string ("") :"".equals(s1);;

If both conditions are met, the string is indeed empty!

String concatenation: Strings in Java can be concatenated by “+”. How does string concatenation in code work in the JVM? As an example, see how the JVM handles string concatenation by comparing the code before and after concatenation string code was compiled.

As you can see from the above example, the JVM does some optimization for string concatenation. If string literals are concatenated, no matter how many strings there are, the JVM will do the same. If the concatenation is between objects, or between objects and literals, or the result of a method execution is concatenated, the StringBuilder is used inside the String to get the value of the object, and the Append method is used to perform the concatenation. It can be concluded that:

  1. A string created using a string literal, that is, by itself""Quoted strings are direct quantities that are stored in the constant pool at compile time;
  2. usenew String("")Objects created are stored in heap memory and created at run time;
  3. Use string concatenators that contain only direct quantities such as"aa" + "bb"Create also direct quantities, such as strings inCompile timeSo it’s going to be stored in the constant pool;
  4. Use containsStringA string expression of a direct quantity (e.g"aa" + s1Objects are created at runtime and stored in the heap because the underlying layer is innovativeStringBuilderObject to achieve concatenation;

5. Either using a variable or calling a method to concatenate a string, the value of the variable and the return value of the method can only be determined at run time. There is no compilation optimization operation.

The common API for String

Here is a list of some common String API, more can refer to the JDK manual, do Java must learn to refer to the JDK manual.

String creation and conversion:

  • byte[] getBytes(): converts the string tobyteThe array.
  • char[] toCharArray(): converts the string tocharThe array.
  • String(byte[] bytes):byteArrays are converted to strings.
  • String(char[] value):charArrays are converted to strings.

Get string information

  • int length(): Returns the length of the string.
  • char charAt(int index)Returns theSpecify the indexPlace thecharValue.
  • int indexOf(String str): Returns the index at the first (left-most) occurrence of the specified string in this string.
  • int lastIndexOf(String str): Returns the index of the last (right-most) occurrence of the specified string in the string.

String comparison judgment

  • boolean equals(Object anObject): compares this string with the specified object.
  • boolean equalsIgnoreCase(String anotherString): compares this String with another String in a case-insensitive manner.
  • boolean contentEquals(CharSequence cs): associates this string with the specifiedCharSequenceCompare, compare is content;
    • The String class implements the CharSequence interface.

** String case conversion: ** The string calling the method is the current string

  • String toUpperCase(): Converts the current string to uppercase
  • String toLowerCase(): Converts the current string to lowercase

StringBuilder/StringBuffer

First to use the String/StringBuilder/respectively StringBuffer to concatenate strings 30000 times, comparing their loss of time, after tests found:

String concatenation is the most time consuming and performance poor because String contents are immutable and new objects are created in memory each time the contents are changed.

The best performance is StringBuilder, followed by StringBuffer, and finally String. StringBuilder is not that different from StringBuffer, or maybe not tested enough. Interested partners can increase the number of splicing to see. The code is pretty simple, so I won’t show you.

Therefore, when developing String concatenation, priority use StringBuffer/StringBuilder, not as a last resort, don’t use String.

StringBuilder and StringBuffer

Both StringBuffer and StringBuilder represent mutable strings, and both ‘function methods are the same. But the only difference:

  • StringBuffer:StringBufferAll methods are used in thesynchronizedModifier, which represents a synchronous operation, can ensure thread-safety when multiple threads are concurrent, but can affect the performance of thread-safety.
  • StringBuilder:StringBuilderNone of the methods in thesynchronizedModifier, which is not thread safe and, because of this, has higher performance.

StringBuilder is recommended for situations where concurrency security is not very high because of its high performance. There will be more cases like this. Using the StringBuilder no-argument constructor, create an underlying char array of length 16:

At this time, the array can only store 16 characters. If the number exceeds 16 characters, the array will be automatically expanded (create a larger array, and copy the previous array to the new array). In this case, the performance is very low. If you know in advance how many characters you want to store, you can use the constructor to set the initial character values:

// Create a char array of length 80. New StringBuilder(80);Copy the code

Common methods of StringBuilder:

  • append(Object val): Appends any type of data to the currentStringBuilderIn the object.
  • StringBuilder deleteCharAt(int index): Deletes the character at the specified position in the string.

The end. Although the old husband is not serious, but the old husband a talent