Indexing mechanism [Java] string



public class T2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str1 = "Java Material";
		String str2 = "Java Material";
		String str3 = new String("Java Material");
		String str4 = str3;
		if (str1.equals(str2)) {
			 System.out.println("str1.equals(str2) : true");
		}
		else {
			System.out.println("str1.equals(str2) : false");
		}
		if (str1.equals(str3)) {
			System.out.println("str1.equals(str3) : true");
		}
		else {
			System.out.println("str1.equals(str3) : false");
		}
		if (str3.equals(str4)) {
			System.out.println("str3.equals(str4) : true");
		}
		if (str1 == str2) {
			System.out.println("str1==str2 : true");
		}
		else {
			System.out.println("str1==str2 : false");
		}
		if (str1 == str3) {
			System.out.println("str1==str3 : true");
		}
		else {
			System.out.println("str1==str3 : false");
		}
		if (str3 == str4) {
			System.out.println("str3==str4 : true");
		}
		else {
			System.out.println("str3==str4 : false");
		}
	}
}

Output:

Result analysis:

summary:

Use the new keyword will re-apply for space in the heap, to open a new area to place the string, not the buffer pool to find whether there had been before the same string

Use = string mechanism will go to find the cache pool if there is the same string before, and if so, just add a hook, share the same memory

Guess you like

Origin blog.csdn.net/chenhanxuan1999/article/details/91397012