current position:Home>Java FAQ -- string

Java FAQ -- string

2022-01-26 22:24:12 Yan Long

String is a common data type . stay Java in , Common string types include StringStringBuffer and StringBuilder.

String

from String You can see the source code of ,String Use an array to store the contents of a string , Arrays use keywords final modification , Therefore, the contents of the array are immutable , Use String The value of the defined string is also immutable .

because String The value of type is immutable , So every time String Any modification will create a new String object , Leads to inefficiency and takes up a lot of memory space .

tips: string Data is stored in a constant pool , Not in the pile also Not in the stack .

StringBuffer and StringBuilder

StringBuffer and StringBuilder All are AbstractStringBuilder Subclasses of , Also use an array to store the contents of a string , Because the array does not use keywords final modification , Therefore, the contents of the array are variable ,StringBuffer and StringBuilder Are all variable types , You can modify the contents of the string , And no new objects will be created due to modification .

When the content of the string needs to be modified frequently , You should use StringBuffer or StringBuilder, Significantly better than... In terms of time and space String.

StringBuffer and StringBuilder What are the differences ? You can see from the source code ,StringBuffer Keywords are used for defined methods or called methods synchronized modification , and StringBuilder The method does not use keywords synchronized modification . because StringBuffer Add synchronization lock to the method , Therefore, its efficiency is slightly lower than StringBuilder, But in a multithreaded environment ,StringBuilder Thread safety cannot be guaranteed , therefore StringBuffer It's a better choice .

summary

String It's an immutable type , Every time the String Any modification will create a new String object , Leads to inefficiency and takes up a lot of memory space , therefore String For string constants , It is not suitable for situations that require a large number of modifications to the string . StringBuffer It's a variable type , You can modify the contents of the string without creating new objects , And StringBuffer It's thread safe , Suitable for multi-threaded environment . StringBuilder It's a variable type , And StringBuffer be similar , In a single threaded environment StringBuilder The efficiency is slightly higher than StringBuffer, But in a multithreaded environment StringBuilder Thread safety is not guaranteed , therefore StringBuilder Not suitable for multi-threaded environment .

copyright notice
author[Yan Long],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201262224096460.html

Random recommended