Java String in the way and create the difference

Create a way

method one:

String name ="wjq";

Method Two:

String name =new String("wjq");

the difference

In order to correct fully explained the difference between the two, may wish to create several groups of strings. Code as follows:
Note that: reference types common method is to compare address (a reference type variable reference type variable == 2), the result is a boolean type, i.e., true / false.

public class Test {

	public static void main(String[] args) {
		String name ="wjq";
		String name1 = "wjq";
		String name2 ="957";
		String name3 =new String("wjq");
		String name4 =new String("wjq");
		System.out.println(name == name1);
		System.out.println(name1 == name2);
		System.out.println(name2 == name3);
		System.out.println(name3 == name4);
		System.out.println(name);
	}

}

The result is:
to true
false
false
false

Direct assignment method, the first address of the variable is stored on the stack, and the contents are present in the constant pool. At the time of the assignment, if the constant pool is not that you want to assign content objects, create new space directly assigned to the variable constant pool, on the contrary, if there is to be assigned the same content object, then return directly to the address of the string.
The first address of the second method, variables stored on the stack, but the content exists in the heap. As long as the definition of new variables, regardless of whether the content is the same, we have opened up a space for storing the first address on the stack, the heap storage number.
By showing an auxiliary understand:
Here Insert Picture Description

Published 19 original articles · won praise 0 · Views 460

Guess you like

Origin blog.csdn.net/zzu957/article/details/104850107