string create objects

Reference http://topic.csdn.net/u/20080929/02/4e0ef626-98ee-4d6d-96ed-fe40afe8290b.html

constant pool constant pool study only String pool here

Create an object with a string two forms

A string form directly given as String str = "222";

2 to create new objects manner as String str = new String ();

In the first string created under way, is on the String pool (string pool) is created when the String object, string pool each string as constants (constants are saved to the constant pool, in fact, not just some string, int char, etc. also), the object is created at compile it, and constants in the string pool is unique, that is, if the two strings are equal only to create an object, such as string str1 = "111"; String str2 = "111"; this is only one object.

Create the following string in the second way, because java is dynamic, object reference points and value types, reference is created at runtime, String is a reference type, when an object is created using new is created at runtime, when when used to create a new object that is stored in the heap each time a new object is created in memory, the comparison is based on comparing the address references, such as String str1 = new String (); String str2 = new String (); this is to create two objects, if they are comparing are not equal, if used String str1 = new String ( "222"); in fact, this is to create two objects, created in java String of when it comes to just constants are saved to the constant pool, because this str1 when creating the incoming parameter "222" this object would have been created at compile time, and only then at runtime values ​​passed a str1, so it is two objects, a constant pool is on (here String pool), is placed in a heap in. The String str1 = new String ( "222"); str1 = str1 + "222"; these two objects is created, as already said, "" format string constant pool is on, and the object constant pool only one.

Guess you like

Origin blog.csdn.net/soliy/article/details/5505281