[Java]
Public class Test {
Public static void stringReplace (String text ){
Text = text. replace ('J', 'I ');
}
Public static void bufferReplace (StringBuffer text ){
Text = text. append ("C ");
}
Public static void main (String args []) {
String textString = new String ("java ");
StringBuffer textBuffer = new StringBuffer ("java ");
StringReplace (textString );
BufferReplace (textBuffer );
System. out. println (textString + textBuffer );
}
}
The answer is javajavaC.
This is the String parameter passed and is immutable ).
In the seventh line of the question, text = text. append ("C"), the append method will change the value in text.
The text and textBuffer in main point to the same object, so the corresponding output is javac.
The value of string will never change!
String a = "a"; // assume that a points to the address 0x0001,
A = "B"; // After the value is re-negative, a points to the address 0x0002, but the "a" saved in the address 0x0001 still exists, but it is no longer pointed to by.
On the surface, the String type object changes the value, but the fact is that it cannot change the value, but can only change the pointed address.
StringBuffer is different. It directly changes the reserved value in the address to which it points.
And
StringBuffer s1 = new StringBuffer ("");
StringBuffer s2 = new StringBuffer ("");
S1.equals (s2) // Why is it false?
String s1 = new String ("");
String s2 = new String ("");
S1.equals (s2) // Why is it true?
The equals method is not redefined in the StringBuffer class, so this method comes from the Object class,
The equals method in the Object class is used to compare the addresses, so it is equal to false.
The equals method is redefined in the String class, and the value is compared, not the address. So yes
True.
I am skeptical about whether or not I can interview a real level.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~
String str = new String ("HELLO ");
String str = "HELLO ";
The above differences are described below
String str = new String ("HELLO"); creates two objects, one being "HELLO", and then creates an object referenced by str using "HELLO.
The following code points str to "HELLO" after "HELLO" is created, so that only one String instance is created.
~~~~~~~~~~~~~~~~~~~~~~~~~
Therefore, the conclusion is that if you operate the content in the String frequently, especially when the content is to be modified, use StringBuffer. If you need a String at the end, use the toString () of StringBuffer () good Way!
Maybe this is the performance bottleneck of your program!
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
A non-mutable object cannot be changed once it is created, and a mutable object can be changed after it is created.
The String object is a non-mutable object, and the StringBuffer object is a mutable object.
To achieve better performance, you need to carefully select one of the two based on your actual situation.