Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use String class, StringBuffer and StringBuilder in Java

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to use String class, StringBuffer and StringBuilder in Java". In daily operation, I believe many people have doubts about how to use String class, StringBuffer and StringBuilder in Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use String class, StringBuffer and StringBuilder in Java". Next, please follow the editor to study!

Basic concepts of String class

The String class belongs to the reference data type, not the basic data type.

In Java, anything in "" (double quotation marks) is a String object.

Java states that strings in double quotes are immutable, meaning that "abc" cannot become "abcd" or "ab" from birth to death.

Strings enclosed in double quotes in JDK are stored in the string constant pool in the method area. (because strings are used frequently in actual development, strings are placed in the string constant pool in the method area for efficiency.)

Storage principle of String string

With String s = "abc", an object is created in the string constant pool in the method area, and s saves the string's address in the string constant pool.

To create an object by String s = new String ("abc"), you will first create a "abc" object in the string constant pool (not again if you already have "abc" in the string constant pool), then create a String class object in the heap area, which stores the address of "abc" in the method area, and s will save the address of the String object in the heap.

Look at the following code:

Public class StringTest01 {/ / these two lines of code mean that three string objects are created, all in the string constant pool String A = "abc"; String B = "abc" + "de" / / to create a string object through new, first look for "abc" in the string constant pool / / if it cannot be found, it will create a "abc" object in the string constant pool / / create a string object in the heap and save the address of "abc" in the string constant pool String C = new String ("abc");}

Draw the JVM memory diagram according to the above code as follows:

Once you know how String class strings are stored, you can easily know the compilation results of the following code:

Public class StringTest01 {public static void main (String [] args) {/ / does not create objects in the heap / / S1 and S2 both store the address "hello" in the string constant pool String S1 = "hello"; String S2 = "hello" / / created objects in the heap / / m _ new String n respectively stores the address of their objects in the heap String m = heap ("Hello!") ; String n = new String ("Hello") ; System.out.println (S1 = = S2); / / the result is true System.out.println (m = = n); / / the result is false}} the common constructors of the String class / / the use of public class StringTest02 {public static void main (String [] args) {byte [] x1 = {97,98,99}; char [] x2 = {'I', 'yes', 'China', 'country', 'human'} / / String s = new String (byte array); String y1 = new String (x1); System.out.println (y1); / / ABC / / String s = new String (byte array, offset, length) String y2 = new String; System.out.println (y2); / / BC / / String s = new String (char array) String y3 = new String (x2) System.out.println (y3); / / I am Chinese / / String s = new String (char array, offset, length) String y4 = new String (x2magin 2); System.out.println (y4) / / Chinese}} commonly used methods in the String class public class StringTest03 {public static void main (String [] args) {/ / public char charAt (int index) method / / return the char type character char S1 = "Chinese" .charat (1); System.out.println (S1) / / country / / public int compareTo (String anotherString) method / / compare two strings System.out.println ("abc" .compareto ("abd")) in dictionary order; / / negative integer System.out.println ("abc" .compareto ("abc")); / / 0 System.out.println ("abc" .compareto ("abb")) / / positive integer / / public boolean contains (CharSequence s) method / / determine whether the string contains s System.out.println ("abcdefg" .string ("efg")); / / true System.out.println ("abcdefg" .string ("hij")) / / false / / public boolean endsWith (String suffix) method / / determines whether the string ends with suffix System.out.println ("abcde" .endsWith ("cde")); / / true System.out.println ("abcde" .endsWith ("qwe")) The / / false / / public boolean equalsIgnoreCase (String anotherString) method / / determines whether two strings are equal, ignoring the case of System.out.println ("ABcd" .equalsIgnoreCase ("abCD")); / / true / / public byte [] getBytes () / / converts the string to an byte array and returns byte [] S2 = "abcdefg" .getBytes (); for (equals I = 0 I < s2.indeth.istring +) {System.out.print (s2 [I] + ");} / / 97 98 99 100 101 102 103 / / public int indexOf (String str) / / determine the index where a substring first appears in the current string / / if the substring does not exist, return-1 System.out.println (" abcdefghigk ".indexOf (" hig ")) / / 7 System.out.println ("abc" .indexOf ("fgh")); / /-1 / / public int lastIndexOf (String str) / / determine the index System.out.println ("abcdhdhdabc" .lastIndexOf ("abc")) that a substring last appeared in the current string / / 8 / / public boolean isEmpty () / / determine whether the string is an empty string / / call the length () method at the bottom, and the empty string length is 0 / / Note: determine that the array length is the length attribute, and the string length is the length () method System.out.println ("" .isEmpty ()). / / true / / public String replace (char oldChar,char newChar) / / returns a new string that replaces all the oldChar in the original string with newChar, without changing the original string String S3 = "aaatttooo"; System.out.println (s3.replace ('tweets / / aaaqqqooo / / public String replace (CharSequence target,CharSequence replacement) / / CharSequence can see that String / / changes all the target in the original string to replacement String S4 = "abcsgdjsssjabcjdjjdjabc"; System.out.println (s4.replace ("abc", "www")) / / wwwsgdjsssjwwwjdjjdjwww / / public String [] split (String regex) / / take regex as the dividing line, save the string in a string array and return String S5 = "2022-3-19"; String [] str = s5.split ("-"); System.out.println (str [0] + str [1] + str [2]) / / 2022319 / / public String substring (int beginIndex) / / returns a string System.out.println ("abcdefgh" .substring (4)) that begins and ends with the index beginIndex / / efgh / / public String substring (int beginIndex,int endIndex) / / returns a substring System.out.println that starts with the index value beginIndex and ends with the index value endIndex (does not contain the characters at the index value) ("abcdefgh" .substring (2p5)) / / cde / / public char [] toCharArray () / / returns a string as a character array char [] str2 = "abcdefg" .toCharArray (); for (int I = 0; I < str2.length; iChart +) {System.out.println (str2 [I]) } / / public String toLowerCase () / / returns a new string System.out.println ("ABcDeFG" .toLowerCase ()) that lowercase all characters in the original string; / / abcdefg / / public String toUpperCase () / / returns a new string System.out.println ("aCbcdEfg" .toUpperCase ()) that capitalizes all characters in the original string. / / ABCDEFG / / public String trim () / / returns a new string System.out.println ("abcdefg" .trim ()) that removes the whitespace before and after the string; / / abcdefg / / public static String valueOf (parameter list) / / parameter list can be int, char, int array, object, and so on. The only static method in the / / String class can directly call / / convert a non-string to a string / / println () the underlying call is the valueOf () method, as long as it is printed on the console is the string System.out.println (String.valueOf (true));}} StringBuffer class

Think about:

What is the impact of frequent use of string concatenation?

Strings are immutable in java, and a new string is generated each time it is spliced.

Strings exist in the string constant pool, and frequent use of string concatenation will take up a lot of method area space.

To avoid the above problems, we can use the StringBuffer class

/ / java.lang.StringBufferpublic class StringBufferTest {public static void main (String [] args) {/ / create an initialization capacity of 16 byte [] arrays (string buffer objects) StringBuffer strBuffer = new StringBuffer () / / the bottom layer of the append () method / / append () method will call the System.arraycopy () method when the splicing string is called. When it is inefficient / / append () to append, it will automatically expand the capacity of strBuffer.append (1) if byte [] is full; strBuffer.append ('q'); strBuffer.append (3.14); strBuffer.append ("abc") System.out.println (strBuffer); / / 1q3.14abc / / StringBuffer can be optimized / / when creating a StringBuffer, it is possible to give an appropriate initialization capacity / / to reduce the number of expansion of the underlying array / / string buffer StringBuffer newstrBuffer = new StringBuffer (100) with specified initialization capacity;}} StringBuilder class

Its usage is very similar to that of StringBuffer, but there are big differences:

All methods in StringBuffer are modified with the synchronized keyword, which means that StringBuffer is safe in a multithreaded compilation environment.

Methods in StringBuilder are not modified by the synchronized keyword, which means that StringBuilder is not safe in a multithreaded compilation environment.

At this point, the study on "how to use String classes, StringBuffer and StringBuilder in Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report