Java puzzles? Characters

  Abstract: Java puzzles? Characters 

  </ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> <table width = "100%" border = "0" cellspacing = "0" cellpadding = " 0 "> <tr> <td width="286" height="86" align="center" valign="top"> </ td> <td width="398" valign="top"> 

  Puzzle 11: The last laugh 

  The following procedures will be printed out? 

  Public class LastLaugh (public static void main (String [] args) (System.out.print ( "H" + "a"); System.out.print ( 'H' + 'a');)) 

  You may think that this process will print HaHa.    The procedure seems to be two ways of H and a link, but you can see the virtual.    If you run this procedure, we will find that it is Ha169 print.    Why, then, it will have such an act? 

  </ Td> </ tr> <tr> <td height="20" colspan="2"> 

  </ Td> </ tr> </ table> 

  As we expect, one pair of System.out.print call Print is Ha: it is the parameters of expression "H" + "a" Obviously, it is implementing a string connected.    And the second on System.out.print call is another question.    The problem is that 'H' and 'a' is a literal character constants, because these two operations are not a few strings, so the implementation of the + operator is additive rather than a string connected. 

  Compiler constants in the expression of 'H' + 'a', it is known through the expansion of our original type-two with the operation of numerical character ( 'H' and 'a') upgraded to achieve numerical int the.    From char to int conversion of the broadening of the original 16 is the numerical zero char extended to the 32 int.    The 'H', char values are 72, and the 'a', char values are 97, therefore expression 'H' + 'a' is equivalent to 72 + int constants 97, or 169. 

  Language stand on the position of a number of similarities between the char and string is illusory.    Language is concerned that char is a 16-bit unsigned integer type of primitive - that's it.    On the class libraries, not so, the class library contains many char acceptable parameters, as Unicode characters and treatment methods. 

  Then you should be how to link characters?    You can use these libraries.    For example, you can use a string buffer: 

  StringBuffer sb = new StringBuffer (); sb.append ( 'H'); sb.append ( 'a'); System.out.println (sb); 

  Can do normal operation, but is very ugly.    In fact, we still have ways to avoid this by the way the Chita lengthy code.    You can ensure that at least one operation for a few strings to compulsory + operators connected to the implementation of a string operation, rather than a Adder operation.    This common usage with an empty string ( "") as a connecting sequence, as follows: 

  System.out.println ( "" + 'H' + 'a'); 

  This usage can ensure that the transition of expression have been to a string.    Although this was very useful, but is somewhat embarrassing, and it may cause some of its own confusion.    Can you guess the following statement will print what?    If you are not sure, then try: 

  System.out.print ( "2 + 2 =" + 2 +2); 

  If you are using the JDK 5.0, you can also use 

  System.out.printf ( "% c% c", 'H', 'a'); 

  In short, the use of the string connecting operators use extra caution.    + Operator if and only if its operation of at least one type String is only when the implementation of the string connecting operation; Otherwise, it is the implementation of the adder.    If the link is not a numerical string type, then you can have several options: 

  •   Preferences an empty string; 
  •   Will be the first to use String.valueOf explicit numerical converted into a string; 
  •   Use a string buffer; 
  •   Or if you use the JDK 5.0 can be used printf methods. 

  This also includes a puzzle to the language designers lesson.    Operator overloading, even in Java only to a limited extent by the support, it will still cause confusion.    Heavy connected to a string + operator and may have been cast is a mistake. 

  Puzzle 12: ABC 

  This puzzles to ask is a pleasant problem, the following procedures will be printed? 

  Public class ABC (public static void main (String [] args) (String letters = "ABC"; char [] = (numbers'1 ','2','3 '); System.out.println (letters + " easy as "+ numbers);))    We hope that this procedure may be printed out ABC easy as 123.    Unfortunately, it did not.    If you run it, they will discover that it is printing, such as ABC easy as [C @ 16f0472 such things.    Why is the output would be so ugly? 

  Despite the char is an integer types, but many libraries have a special deal with them, because char numerical characters is often said that instead of integers.    For example, a char values will be passed to the method println print out a Unicode characters instead of its digital code.    An array of characters by the same special treatment: the char [] println Heavy print version will be covered by an array of all the characters, and String.valueOf and StringBuffer.append the char [] Heavy duty version of the act is similar. 

  However, the string connecting operators in these methods have not been defined.    The operator is defined as the first operation of its implementation string, and then connect the two strings together.    , Including an array of object reference string conversion defined as follows [JLS 15.18.1.1]: 

  If cited as null, it will be converted to the string "null."    Otherwise, the implementation of the conversion is not like any parameter called the Object toString method invoked the same, but if the call is the result of toString method null, then used string "null" in place. 

  Then, in a non-air above char array toString method will be called to the kind of behavior?    Object array inherited from the toString method [JLS 10.7], standardized described: "returns a string that contains the object of their names, '@' symbol, and that object hash code of a non - Symbol hex integer "[Java-API].    Class.getName related to the normative description: char [] type of object called the method of the results of the string "[C."    Will link them together we created in the process of printing out that the ugly string. 

  There are two ways this can be revised procedures.    You can connect a call to the string before the explicit will be converted into an array of a string: 

  System.out.println (letters + "easy as" + String.valueOf (numbers));    Or, you can call decomposition System.out.println calls for the two to take advantage of the char [] println Heavy version: 

  System.out.print (letters + "easy as"); System.out.println (numbers);    Please note that these revised only you call the valueOf method println, and the heavy-duty version of the correct circumstances, be in normal operation.    In other words, they are strictly dependent on the compiler used an array of types. 

  Below the description of the procedures for this dependence.    It looks like the second described a concrete realization of the revised approach, but it is the output produced with the initial output generated by the process as ugly as it is called the Object println Heavy version, rather than char [ ] heavy-duty version. 

  Class ABC2 (public static void main (String [] args) (String letters = "ABC"; Object numbers = new char [] ('1 ','2','3 '); System.out.print (letters + "easy as"); System.out.println (numbers);))    In short, char array is not the string.    To a char array will be converted into a string, it is necessary to call String.valueOf (char []) method.    Some libraries in the method of delivery of an array of char string of similar support, usually is to provide a heavy-duty version of the Object methods and a char [] version of the heavy-duty, and after which we want to produce act. 

  The language designer lesson is: type char [] may be overwritten toString method, it contains an array of characters.    More generally, the array type may override the toString method should be to return to the content of a string array that. 

  Puzzle 13: farm 

  George Orwell's "Animal Husbandry Course (Animal Farm)," a book readers may remember that the old Colonel Declaration: "All animals are equal." Below the Java program trying to test the declaration.    Well, it will print out? 

  Public class AnimalFarm (public static void main (String [] args) (final String pig = "length: 10"; final String dog = "length:" + pig.length (); System.out. Println ( "Animals are equal : "+ == pig dog);))    Surface analysis of the procedure might think that it should be printed out Animal are equal: true.    After all, pig and dog are final type of string variables are initialized to their character of the "length: 10."    In other words, pig and dog was quoted string is and will always be their equivalent.    However, the == operator test is whether these two object reference is applied to the same object.    In this case, they are not applied to the same object. 

  You may know the type String constants is the compiler of the memory limit.    In other words, any two types of String constants expression, if identified is the same sequences of characters, then they will use the same object reference to that.    If constant expression to initialize pig and dog, then they will certainly point to the same object, but the dog is not initialized by the constant expression.    Since the language has been in constant expressions allow the operation to the limit, and method in which the call is not, then, this procedure should print Animal are equal: false, right? 

  Ah, in fact wrong.    If you run the program, you will find it printed only false, and not any other things.    It did not print Animal are equal:.    It will not print how this string literal constant?    After all, it is the correct print!    Puzzle 11 of the programme includes a mystery that: + operator, or whether the string is used to connect addition, it == operator than a high priority.    Therefore, the method println parameters are calculated in the following manner: 

  System.out.println (( "Animals are equal:" + pig) == dog);    Boolean expression of the value of this is of course false, it is the procedure by the print output. 

  One sure to avoid such a predicament: in the use of strings connecting operator, always will be non-trivial operation with a few brackets enclose.    More generally, when you can not determine whether you want the brackets, should be chosen and properly, they will enclose.    If you println statements like this compared to enclose part, it will have the desired output Animals are equal: false: 

  System.out.println ( "Animals are equal:" + (pig == dog));    Arguably, the process is still a problem. 

  If you can, you should not rely on the code in the string constants, limited memory mechanism.    Limited memory mechanism is designed to reduce the amount of memory virtual machine, it is not as a programmer can use a tool designed.    Like this puzzle shows, which will have a string constant expression is not always apparent. 

  Worse still is that if you rely on the code memory limit mechanism to bring about the correctness of operation, then you must be careful to understand what parameters must be the domain and limited memory.    Compiler will not help you to check these variables, because of the limited memory and limited use the same type of strings (String) said.    These limited because of the string in memory caused by the failure is a very difficult bug to detect. 

  In comparing object reference, you should be given priority in the use equals methods rather than == operator, unless you need to compare the logo object is not the object value.    Through the application of this lesson to our procedures, we are given the following statement println This is the way it should have.    Clearly, in this way the revised procedures, it will print out true: 

  System.out.println ( "Animals are equal:" + pig.equals (dog));    The puzzle of language designers have two lessons. 

  •   String connected priority and should not be the same additive.    This means that override + operator to implement the string connection is a problem, as mentioned in the 11 puzzles in the same. 
  •   There is, the type can not be modified, such as String, quoted the equivalence ratio of the equivalent of more people are confused about.    Perhaps == operator in the application can not be modified by the type of implementation should be compared.    To achieve this, a method is the == operator as equals simple method of writing, and provide a separate System.identityHashCode similar to the method used to implement the logo comparison. 

  Puzzle 14: Escape characters defeat 

  Below the use of the procedures of the two escaped Unicode characters, and they are using the hexadecimal code that Unicode characters.    So, this procedure would print? 

  Public class EscapeRout (public static void main (String [] args) (/ / \ u0022 is the double quotes escaped Unicode characters System.out.println ( "a \ u0022.length () + \ u0022b." Length ()) ;))    In the process of a very superficial analysis would think that it should be printed out 26, because the two pairs of quotes from "a \ u0022.length () + \ u0022b" logo string between a total of 26 characters. 

  A little in-depth analysis that will be the view that the procedure should be Print 16, because the two escaped Unicode characters each in the source file needs to six characters, but they only said that a string of characters.    Therefore, the string should be the appearance of it than to be short of its 10 characters.    If you run this procedure, we will find that things are not that far from the case.    It is neither 26 print is not 16 but 2. 

  The key to understanding this puzzle is to know: Java in the string literal constant escaped Unicode characters did not provide any special treatment.    Compiler in a variety of analytical procedures will sign before the first escaped Unicode characters transformed into that of the characters they [JLS 3.2].    Therefore, the first procedure escaped Unicode character as a single-character string literal constant ( "a") quotes the end, and the second escaped Unicode characters as another single-character string literal constant ( "b ") began quotes.    Printing is the expression "a." Length () + "b." Length (), or 2. 

  If the procedures are certainly hope that the author of such acts, the following statement will be more clearly: 

  System.out.println ( "a." Length () + "b." Length ());    More likely situation is that the author hopes will be two pairs of characters placed in quotation marks the internal string literal constant.    Escaped use Unicode characters you achieve this, but you can use escape sequences of characters to achieve [JLS 3.10.6].    One pair of quotation marks that the escape sequences of characters is a backslash followed behind a double quotation marks (\ "). If the initial proceedings in the Unicode character escape sequence with escaped characters to replace, it will print out the desired 16: 

  System.out.println ( "a \." Length () + \ "b." Length ());    Many of the characters have escaped the corresponding sequences of characters, including the single quotes (\ '), newline (\ n), tabs (\ t) and backslash (\ \).    You can literally character string literal constant constants and the use of escape sequences of characters. 

  In fact, you can use as octal escape characters special type of escape sequences of characters, any ASCII characters will be placed in a string literal constant character or a literal constant, but the best is to use ordinary the escape sequences of characters. 

  The general escaped character sequences and octal escape escaped Unicode characters than the characters much better, because different characters and Unicode escaped, escaped character sequences in the analytical procedures to be processed after all the symbols. 

  ASCII character set is the smallest public feature set, it only 128 characters, but there are more than 65,000 Unicode characters.    An escaped Unicode characters can be used only in the use of ASCII characters in the procedure to insert a Unicode characters.    Unicode characters escaped a precise equivalent to that of the characters in it. 

  Unicode character was designed to escape the programmers need to insert a source file can not be said of the characters in character set of circumstances.    They will be mainly used for non-ASCII characters placed identifier, string literal constant, literal character constants and Notes.    Occasionally, escaped Unicode characters also be used to look quite similar in a number of characters clearly labelled one of a certain, thereby increasing the clarity of procedures. 

  In short, in the literal character string and constants, we should give priority to the escape sequences of characters, and not escaped Unicode characters.    Unicode characters escaped because they could be compiled in a sequence which has been dealing with premature and cause confusion.    Do not use Unicode characters escaped to express ASCII characters.    And the characters in the string literal constant, we should use escape sequences of characters; literal constants for the addition of these circumstances, should be directly inserted into ASCII characters in the source document. 

  Puzzle 15: It is to turn the Hello 

  Below is a procedure known examples of the changes made after a little bit version.    Well, it will print out? 

  / ** * Generated by the IBM IDL-to-Java compiler, version 1.0 * from F: \ TestRoot \ apps \ a1 \ units \ include \ PolicyHome.idl * Wednesday, June 17, 1998 6:44:40 o'clock AM GMT +00:00 * / public class Test (public static void main (String [] args) (System.out.print ( "Hell"); System.out.println ( "o world");))    This puzzle looks quite simple.    The program includes two sentences, the first print Hell, and the second in the same line of print o world, which will effectively link the two strings in them.    Therefore, you might expect the program print Hello world.    But unfortunately, you have committed a wrong, in fact, it simply passed compiler. 

  The problem is that Notes of the third line, which includes the characters \ units.    These characters to backslash (\), as well as keeping up with the letter u in the beginning, and it (\ u) is a Unicode characters escape the beginning.    Unfortunately, these characters did not keep up with the back four hexadecimal number of places, thus escaping the Unicode characters are in conformation, and the compiler was refused a request procedures.    Unicode character must escape the structure is good, even if there is in the Note as well. 

  In the Note insert a good structure escaped the Unicode character is legitimate, but we have little reason to do so.    Sometimes programmers JavaDoc Notes will be used in the escape Unicode characters in the document with special characters. 

  / / Unicode escaped characters in the JavaDoc Notes in the usage / ** * This method calls itself recursively, causing a * StackOverflowError to be thrown. * The algorithm is due to Peter von der Ah \ u00E9 * /    The technology that has escaped Unicode characters a little utility usage.    Notes in the Javadoc, HTML entities should be used to replace the Unicode characters escaped escaped characters: 

  / ** * This method calls itself recursively, causing a * StackOverflowError to be thrown. * The algorithm is due to Peter von der Ahé * /    Two in front of the Notes should be in the document is the name "Peter der Ahé," but after a note in the source file is understandable. 

  Perhaps you would be very much surprised, in this puzzle, the problem of this information in the Notes ↑ Back 

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

Recommend Articles

Comments

Leave a Reply