Java (2) puzzle 11-23

Source: Internet
Author: User

In the previous article, we recorded 10 puzzle, mainly about expressions. One key of expressions is to have values. Therefore, many puzzles are centered around the data type, what we want to share today is the character puzzle, no matter whatProgramming LanguageThe character is always a good question. I have also summarized some performance problems of the string in Java before. I found that I have read these 13 puzzle and have deepened my understanding.

Puzzle 11 final laughter
 
Public ClassLastlaugh {Public Static VoidMain (string ARGs []) {system. Out. Print ("H" + ""); System. Out. Print ('H' + 'A');}}

 

This problem is still very simple. The first line must print ha, but the second line is different. This is the addition of two characters, we know that the addition of the two characters will be upgraded to the addition of the int type, so it is actually the addition of 72 and 97. One solution is system. Out. Print ("" + 'H' + 'A'). This is a very quick way to convert other data types into strings.

 

Puzzle 12 ABC
 
Public Class ABC {public static void main (string [] ARGs) {string letters = "ABC"; char [] numbers = {'1', '2 ', '3'}; system. out. println (letters + "Easy as" + numbers );}}

 

Perhaps those who have studied the string may think that printing numbers will print the string out of course, because stringbuilder itself is also implemented using character arrays, however, the result of this example is ABC easy as [c @ 2e6e1408. We can see that the object name is later. The reason is that the tostring method is called when the char array is to be converted to a string. This method is inherited from the object, so the above result is printed. HoweverCodeIf numbers is printed directly, the problem does not occur because the system. Out. println method reloads the character array parameters so that it can print the contents of the array normally.

 

Puzzle 13 Animal Farm
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 );}}

 

If you don't want to close the customs, the printed result is false (which may be much worse than you think ). There are two traps here. The first one is about string initialization. This problem will confuse some students who have studied string, because the strings referenced by pig and dog are the same, = compare whether the referenced object is the same (the C idea is to compare the address), and according to the characteristics of the Java String constant pool (some introduction references ), for any constant expression of the string type, if the same string is specified, they will point to the same object, so we think the possible result is animals are equal: True. Otherwise, use = to determine whether pig and dog will get false. The reason is that the dog Initialization is not a constant expression. I suddenly found myself ignoring this problem. You can test the code by writing two lines.

So why not print "animals are equal? The reason is the operator priority problem. The + priority is higher than =, so this expression is actually compared with "animals are euqal: Length: 10" and "Length: 10 ", therefore, false is printed directly. This revelation is that when multiple operators are involved in an expression, we must add parentheses when we are not sure about the priority. System. Out. println ("animals are equal:" + (pig = dog ));

 

Failure of puzzle 14 escape characters
 
Public class escaperout {public static void main (string [] ARGs) {// \ u0022 is the Unicode escape for double-quote (") system. out. println ("A \ u0022.length () + \ u0022b ". length ());}}

 

Background \ u0022 represents Unicode double quotation marks. ThisProgramTwo possible results are as follows: print the printed content as the entire string, and escape \ u0022 first. In fact, it is the first transfer operation, which is completed before compiler parsing. So the program becomes system. Out. println ("A". Length () + "B". Length ());,. This tells us to try not to use Unicode escape characters.

 

Puzzle 15 confusing hello
 
/*** Generated by the ibm idl-to-Java compiler, version 1.0 * from F: \ testroot \ apps \ A1 \ units \ include \ policyhome. IDL * Wednesday, June 17,199 8 6:44:40 o 'clock am GMT + */public class test {public static void main (string [] ARGs) {system. out. print ("hell"); system. out. println ("O world ");}}

 

In fact, if you put this Code directly in your eclipse, you will find the problem and report an error, which is the comments part. Note that there is a \ U in the comments of the second line, which indicates the start of Unicode transfer character, but it is not an identifiable hexadecimal number, so the program reports an error. It hurts, right?

The problem is that many of these annotations are automatically generated, and they are represented by a backslash at the directory level in windows, which can easily lead to problems. So if an error is reported in comments one day, Search \ U and try again.

 

Puzzle 16-line printing program
 
Public class lineprinter {public static void main (string [] ARGs) {// Note: \ u000a is Unicode representation of linefeed (LF) Char c = 0x000a; system. out. println (c );}}

 

This example is also quite painful because it is still related to Unicode transfer in the annotation. In fact, before the compiler removes the empty lines and comments in the code, unicode has been replaced with a transfer character, while \ u000a represents a line break, so we can find the problem. This comment will be split into two lines, and an error will naturally be reported, unicode.

 

Puzzle 17, huh?
\ Users \ u0075 \ u0062 \ Users \ u0069 \ u0063 \ u0020 \ u0020 \ u0020 \ u0020 \ u0063 \ Users \ u0061 \ u0073 \ u0073 \ u0020 \ u0055 \ u0067 \ transaction \ \ Users \ u0070 \ u0075 \ u0062 \ Users \ u0069 \ u0063 \ u0020 \ u0020 \ u0020 \ u0020 \ u0020 \ u0020 \ u0020 \ u0073 \ u0074 \ u0061 \ Users \ \ Users \ u0069 \ u0064 \ u0020 \ u006d \ u0061 \ u0069 \ Users \ u0028 \ u0053 \ u0074 \ u0072 \ u0069 \ Users \ u0067 \ u005b \ u005d \ u0020 \ \ Users \ u0020 \ u0020 \ u0020 \ u0061 \ u0072 \ u0067 \ u0073 \ u0029 \ u007b \ u0053 \ u0079 \ u0073 \ u0074 \ u0065 \ u006d \ Users \ Users \ u0070 \ u0072 \ u0069 \ Users \ u0074 \ Users \ u006e \ u0028 \ u0020 \ u0022 \ u0048 \ u0065 \ Users \ u0020 \ u0077 \ u0022 \ u002b \ u0022 \ u006f \ u0072 \ u006c \ u0064 \ u0022 \ u0029 \ u003b \ u007d \ u007d

 

Actually .. This is a piece of executable code. The author points to us and does everything .. .. No .. Yes .. .. .. Unicdoe

 

Puzzle 18 string cheese
Public class stringcheese {public static void main (string ARGs []) {byte bytes [] = new byte [256]; for (INT I = 0; I <256; I ++) bytes [I] = (byte) I; string STR = new string (bytes); For (INT I = 0, n = Str. length (); I <n; I ++) system. out. print (INT) Str. charat (I) + "");}}

 

This program first converts the number to a byte array, then generates a string using the byte array, and then converts each character in the string to an int to print it out. In normal thinking, we want to see the numbers 0--255, but it is actually uncertain. The problem is that when defining a new string, because bytes is defined and the character set is not specified, the API mentions that the array length is a function of the character set, therefore, if not specified, an uncertain length occurs.

Many developers who have developed J2EE should be very familiar with the other method of initializing string with byte, that is, passing in the second character set parameter, which is often used for unified encoding during website development, especially Chinese garbled characters.

 

Puzzle 19 beautiful sparks
Public Class Classifier {public static void main (string [] ARGs) {system. out. println (classify ('n') + classify ('+') + classify ('2');} static string classify (char ch) {If ("0123456789 ". indexof (CH)> = 0) Return "numeral"; if ("abcdefghijklmnopqrstuvwxyz ". indexof (CH)> = 0) Return "letter";/** (operators not supported yet) * If ("+-*/& |! = ". Indexof (CH)> = 0) * return" operator "; */Return" unknown ";}}

 

The problem in this example can be seen in fact, that is, the first/* of the block comment statement matches the */in the Code, resulting in a mess of the entire code. This is a classic problem caused by block annotations. The book also shows that block Annotations do not support nesting. In this puzzle, the author also mentioned a comments method that programmers like to use, that is, to put a piece of code in the block of IF (false) {}, which is also prone to problems, it is not recommended for debugging convenience.

 

Puzzle 20 what is our class?
Package COM. javapuzzlers; public class me {public static void main (string [] ARGs) {system. out. println (Me. class. getname (). replaceall (". ","/") + ". class ");}}

 

This example is very simple. His intention is to print out the class name com. javapuzzlers. Me and then replace. With/to get the specific directory of this file. Note that the first parameter of replaceall is a regular expression ,". "In the regular expression, I believe everyone knows that it matches any character, and the result is changed //////. There are two solutions. One is to write the correct regular expression, that is, "\.". The second method is to use the quote method of patern to directly represent the content to be matched.

There is a hidden risk. We can get the desired result as soon as possible: COM/javapuzzlers/ME. class, it is only useful on Unix/Linux, and the directory on Windows uses a backslash, so it becomes invalid. The following puzzle will involve this issue.

 

Puzzle 21 what is our class shot 2?
 
Package COM. javapuzzlers; import Java. io. file; public class metoo {public static void main (string [] ARGs) {system. out. println (metoo. class. getname (). replaceall ("\\. ", file. separator) + ". class ");}}

 

This should be a modified version of the previous problem. In Windows, the problem may occur because of file. the separator is a backslash, which is used as an alternative parameter here. Unlike a normal string, it needs to be transferred, so an error will occur. The current JDK provides the replace method, which is more suitable for handling simple cases. Both parameters are common strings, saving a lot of problems.

 

Puzzle 22 URL Spoofing
 
Public class browsertest {public static void main (string [] ARGs) {system. out. print ("iexplore:"); http://www.google.com; system. out. println (": Maximize ");}}

 

In fact, I just discovered this feature of Java, the statement label. The Goto in C language has used the statement label. In fact, when I write it here, I still don't know what the function of the statement label in Java is and why he designed it like this. In this example, http: is a label. It is followed by a line of comment, so the Code has no problem and can be executed completely.

 

Puzzle 23
Import Java. util. *; public class rhymes {Private Static random RND = new random (); public static void main (string [] ARGs) {stringbuffer word = NULL; Switch (RND. nextint (2) {Case 1: Word = new stringbuffer ('P'); Case 2: Word = new stringbuffer ('G'); default: WORD = new stringbuffer ('M');} Word. append ('A'); word. append ('I'); word. append ('n'); system. out. println (Word );}}

 

The last puzzle in this chapter is my favorite. I only found one of the three traps. That is, we find that there is no break in every case, so the final results cannot print pain and gain. There are two traps. One is about generating random numbers. The nextint parameter is set to 2 and can only generate two random numbers 0 and 1. The correct syntax is that the parameter is 3.

Next, the most interesting trap is that the final result can only print ain, which is strange. In fact, the problem lies in the initialization of stringbuffer, and stringbuffer has no character as the parameter constrtor, there are only three constructor types. One is non-parametric, but the other is string, and the other is int (the initial capacity is discussed in detail ), therefore, in stringbuilder ('M'), the character m is treated as an int, so the above statement is equivalent to initializing the capacity for the stringbuilder knowledge. This is a very good puzzle, which is much more fun than the previous one.

 

Chapter3 is concerned with the character puzzle. Four puzzle addresses the problem caused by Unicode transfer characters, and some issues between char and string. The last example is the most beneficial, in particular, it reminds us of the initialization of stringbuilder. It is not hard to find that good programming habits can help us avoid many problems, read puzzle, and become smarter. The next chapter is the mystery of the loop. It will be better.

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.