Java object-oriented basic String class
Two instantiation methods of the String class
A. Direct assignment
Public class Stringlei {public static void main (String args []) {String name = "zhangsan"; System. out. println ("name:" + name );}}
B. Use the keyword new
Public class Stringlei {public static void main (String args []) {String name = new String ("Zhang San"); System. out. println ("name:" + name );}}
String Content Comparison
1. Use "=" to compare
public class Stringlei{public static void main(String args[]){ String str1="hello"; String str2=new String("hello"); String str3=str2; System.out.println("str1==str2?-->"+(str1==str2));//false System.out.println("str1==str3?-->"+(str1==str3));//false System.out.println("str2==str3?-->"+(str2==str3));//true}}
We can see that: "=" determines whether the address space is equal to the address space. To determine the content, you must use the equals () method provided in String to complete the process:
public class Stringlei{public static void main(String args[]){ String str1="hello"; String str2=new String("hello"); String str3=str2; System.out.println("str1==str2?-->"+(str1.equals(str2)));//true System.out.println("str1==str3?-->"+(str1.equals(str3)));//true System.out.println("str2==str3?-->"+(str2.equals(str3)));//true}}Differences between the two instantiation Methods
You can use the direct value assignment and new call constructor in the String. Compare two methods.
A String is an anonymous String object.
Public class Stringlei {public static void main (String args []) {String str1 = "hello "; // actually, the heap memory space is directed to the stack memory space String str2 = "hello"; String str3 = "hello"; System. out. println ("str1 = str2? --> "+ (Str1 = str2); // true System. out. println (" str1 = str3? --> "+ (Str1 = str3); // true System. out. println (" str2 = str3? --> "+ (Str2 = str3); // true }}
The content of the string cannot be changed.
public class Stringlei{public static void main(String args[]){ String str="hello"; str=str+" world!"; System.out.println("str = " +str);}}
Here, the content in str is not simply changed, for example: