String objects

  String object yqj2065 (Yan Qian-Jun) → 

  CSDN recent forum to look at some of the questions users paste, which on the issue of String often mentioned.    I have always thought he is very clear this thing, but in fact get to the bottom, find themselves not so clear, will make some mistakes it has also produced a number of Lenovo.    Summary of this. 

  1, "abc" and the new String ( "abc"); 

  Often ask questions to the surface: String s = new String ( "abc"); created several String Object? [Such as the number of objects created here? And a small face questions: 

  This problem is relatively simple, involving a knowledge include: 

  •   Use variables and object distinction; 
  •   Text string "abc" is a String object; 
  •   [Pool [pool of literal strings] and stack [heap] String object. 

  1, cited variables and objects: In addition to some of the early books and now the Java garbage books, people can see more clearly and to learn the difference between the two.    A aa; sentence of the statement cited a class A variable aa [I often call handle], and the general adoption of new objects created.    Therefore, the title is a quote s only variable, it is not a target.    [Ref handle, and use objects] 

  Second, all of the Java string [[string constants] is a String objects.    Some people [in particular C programmers] in a number of occasions like the string "as / as" an array of characters, there is no way, because of the string and an array of characters, there are some intrinsically linked.    In fact, it is an array of characters and two entirely different audiences. 

  System.out.println ( "Hello." Length ()); 
  Char [] (cc = 'H', 'i'); 
  System.out.println (cc. length); 

  Third, the creation of a string object: string object because the use of large quantities [it is a target, in general object in the heap always allocate memory], Java in order to save memory space and run-time [such as string comparison, == than equals () Express], when they compile all the text into a text string pool [pool of literal strings], and [running Chi Chi part of a constant.    [Pool the benefits of the pool is all the same string constants are merged, only occupying a space.    We know that the use of the two variables, the use == judge their value is equal to [use] that point to the same object: 

  String s1 = "abc"; 
  String s2 = "abc"; 
  If (s1 == s2) 
  System.out.println ( "s1, s2 refer to the same object"); 
  Else System.out.println ( "trouble"); 

  Here shows that the output of two text strings for the preservation of an object.    That is to say, only in the above code in the creation of a pool String object. 

  Looking at the present String s = new String ( "abc"); statement here "abc" in the pool itself is an object, and in run-time implementation of new String (), will be in the pool put a copy of the object in the heap , and the heap of this object to the application of s holders.    Ok, this statement would create two String objects. 

  String s1 = new String ( "abc"); 
  String s2 = new String ( "abc"); 
  If (s1 == s2) (/ / will not enforce the sentences) 

  Then use == judgement on, we can see that while the two targets of the "content" of the same [equals () judgement], but the two variables used by some quoted different, 

  BTW: The above code to create a number of String Object? [3, in a pool, two in the heap.  ]
  [Java2 certification exam study guides (No. 4) (English) p197-199 are illustrated.  ]


  2, strings and string operations + 

  String conversion and connected in series is the basis of content, I thought that the problem simply send sub-themes.    In fact, I had to explanations of the errors. 

  String str = new String ( "jf"); / / jf transfer points 
  Str = 1 +2 + str +3 +4; 
  Create a total of the number of String objects?    [I began to answer: five.    Jf, new, 3jf, 3jf3, 3jf34] 

  JLS first look at the exposition: 

  A string environment [JLS 5.4 String Conversion] 

  String environment merely means the use of dual + operator of one operand is a String object.    In this particular case, several operations into another String, in the expression of these two is the result of the rods String. 

  Second, rods operator [JLS 15.18.1 String Concatenation Operator +] 

  If an operator / String is the type of expression, in another operation of running into a String object, and the two connected in series.    At this time, any type can be converted into String.    [Here, I missed the "3" and "4"] 

  •   If the basic data types, as its packaging converted into first class objects, such as int x convert as Integer (x). 
  •   Now quoted unify all types of conversion to the String.    As such conversion [as if] call the object's toString method without parameters.    [If it is null then converted into "null"].    ToString method as defined in the Object, it has all the categories, and Boolean, Character, Integer, Long, Float, Double, and String rewrite of the method. 
  •   About + is connected in series or additive, by the operator of a decision.    1 +2 + str +3 +4 is very easy to know "jf34."    [BTW: 15.18.1.3 in the JLS cited in a jocular little example, it is really boring.  ]

  The following example test rewrite toString method situation.. 

  Class A ( 
  Int i = 10; 
  Public static void main (String [] args) ( 
  String str = new String ( "jf"); 
  Str + = new A (); 
  System.out.print (str); 
  ) 

  Public String toString () ( 
  Return "ai =" + i + "\ n"; 
  ) 
  ) 

  3, string conversion optimization 

  According to the above argument, str = 1 +2 + str +3 +4; statement should seem to be generating five String object: 

  1.   1 +2 = 3, then 3 → Integer (3) → "3" in pool? [Hypothetical case] 
  2.   "3" + str (in heap) = "3jf" (in heap) 
  3.   "3jf" +3, first 3 → Integer (3) → "3" in pool? [Not create] then "3jf3" 
  4.   "3jf3" +4 create "4" in pool 
  5.   Then "3jf34" 

  3,4 here it is not clear whether the string conversion in the pool, so the result is still speculation. 

  In order to reduce the creation of the intermediate string object, connected in series and repeatedly enhance the performance of computing, a Java compiler can use StringBuffer or similar technology, or to convert into step with the rods.    For example: For a + b + c, Java compiler can be regarded it as [as if] 

  New StringBuffer (). Append (a). Append (b). Append (c). ToString (); 

  Note that the basic types and invoke types, in the append (a) will be first in the course of conversion parameters, from this point of view, str = 1 +2 + str +3 +4; create a string may be a "3", "4" and "3 jf34" [as well as a StringBuffer object]. 

  Now, I still do not know how to answer str = 1 +2 + str +3 +4 has built a number of String objects,.    Perhaps, on this issue does not have to be at least SCJP not test it. 

  3, which is different: str = "3" + "jf" + "" + "4"; 

  If it is a text string composed entirely by the expression, in the compiler, has been optimized and not at run-time creation of the middle string.    Test code as follows: 

  String str1 = "3jf34"; 
  String str2 = "3" + "jf" + "" + "4"; 
  If (str1 == str2) ( 
  System.out.println ( "str1 == str2"); 
  Else () 
  System.out.println ( "think again"); 
  ) 
  If (str2.equals (str1)) 
  System.out.println ( "yet str2.equals (str1)"); 

  Clearly, str1 and str2 point to the same object, and this object in the pool.    All follow the Java Language Spec compiler must be compiled with the constant expressions can be simplified.    JLS: Strings computed by constant expressions (ý15.28) are computed at compile time and then treated as if they were literals. 

  The String str2 = "3" + "jf" + "" + "4"; we say that only the creation of a target.    Attention, "the number of objects created," said the discussion is the creation of run-time object. 

  BTW: Compiler Optimization 

  String x = "aaa" + "bbb"; 
  If (false) ( 
  X = x + "ccc"; 
  ) 
  X + = "ddd"; 

  Equivalent to: 

  String x = "aaa bbb"; 
  X = x + "ddd"; 

  4, the same category 

  String object is immutable (immutable).    Some of str = 1 +2 + str +3 +4; statement questioned how the content can be changed str?    In fact remains unclear because: invoke the distinction between variables and objects.    Str variable is only invoked, the value of it - it can change the application of holders.    You constantly create new objects, I constantly changing direction.    [Reference TIJ the Read-only classes.  ]

  The same type, the key is to target all the operations are unlikely to change the original object [if necessary, on return to a change of the new object].    This object irrevocable guarantee.    Why should a class designed the same category?    A OOD design principles: Law of Demeter.    Its broad interpretation is: 

  Use the same category.    Wherever possible, the category to be the same type design. 

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • DotNetKicks
  • DZone
  • Netvouz
  • Propeller

Tags: ,

Releated Java Articles

Comments

Leave a Reply