In Java, strings can be assigned directly or created using new, The direct assignment is that the string value is placed in the constant pool in the compile phase (. class file), and the memory space is no longer allocated if other variables are directly assigned to the same value, but instead it is given a reference address, whereas using new to create the space that is allocated when the program is run is a new reference address that can be inter The () method adds a string to the constant pool, and returns its reference if the string already exists in the constant pool. In the string class, = = is the same as the reference address for comparing two strings, and equals compares the values of both (= = and equals in other reference classes). Take a look at an example to deepen your understanding:
- String s1="sa";
- String s2="sa"; Make S1 and S2 point to the same reference address at compile time
- String s3=new String ("sa"); A new reference address is given to S3 when the program is run
- String s4=new String ("sa"). Intern (); When the program runs, it returns the reference address pointed to by S1 and S2 to S4.
- System.out.println (S1==S2);
- System.out.println (s1.equals (S2));
- System.out.println (S1==S3);
- System.out.println (S1.equals (S3));
- System.out.println (S1==S4);
- System.out.println (S1.equals (S4));
- System.out.println (S3==S4);
- System.out.println (S3.equals (S4));
Output Result:
- True
- True
- False
- True
- True
- True
- False
- True
The memory allocation mechanism for C # is not well understood, the difference between = = and equals in the string class is verified by the program, and you can see that both = = and equals are comparison values equal (in other reference classes = = Default comparison reference address, equals default comparison value):
- string S1 = "SB";
- String s2 = "SB";
- char[] t={'s ',' B '};
- String s3 = new String (t);
- Console.WriteLine (S1 = = s2);
- Console.WriteLine (S1. Equals (S2));
- Console.WriteLine (S1 = = S3);
- Console.WriteLine (S1. Equals (S3));
Output Result:
- True
- True
- True
- True
Please also point out if there is any mistake in the summary.
The difference between string direct assignments in Java and C # and the use of new creation (= = vs. equals)