Java (1) puzzle 1-10

Source: Internet
Author: User

I took the book Java confusing again from the library. Now I want to repeat it again. Unlike reading this book in my junior year, I decided to take some notes. Take some time every day to read some puzzle to make the dull brain clearer. When reading every puzzle in this book, it feels like Fan Wei's Role in the sketch, it is often said that "this is the case ". However, the difference is that reading puzzle makes people smarter, rather than being fooled. So I decided to write a series and read it in one breath from the weekend to the next week. All of the following are described in your own language. They are just some of your own understandings. Just write down and record your thoughts. If you haven't read this book, go directly to the original version. 10 puzzle per day takes ten days. Although it will waste some time, it is always better than it hurts for a few days on Weibo and various SNS. "Oh, it's the end of the world in XX days ..". Let's get down to the truth.

The first chapter is the mystery of expressions. It mainly utilizes some standard specifications of Java language, and some errors are caused by non-standardCodeWritten.

Puzzle 1 odd

 
Public static Boolean isodd (int I) {return I % 2 = 1 ;}

This is a method for determining parity. Is there anything wrong with it?

Of course, is this an incomplete method? If-1 is not taken into account, the negative odd number modulo 2 will get-1. Therefore, in this judgment, only the odd number of positive numbers can return true. If 0 is used to determine the effect, the above error can be avoided. In fact, from the semantic point of view, 0 is more reasonable. We did not learn it long ago. Odd numbers cannot be divisible by 2, instead of saying, "an odd number is the number that is divided by two and has one division ". A good solution provided in the book is return (I & 1 )! = 0. Although it looks smart, it is not as intuitive as the modulo.

 

Puzzle 2 Change Time

 
System. Out. println (2.00-1.10 );

This is more refined. I thought it would print 0.90, but the result is 0.89999999.

The reason is that double cannot accurately represent decimal places such as 0.1. I ignored this problem. The floating point type is 1010.10101. Similar to decimal, each digit has a corresponding weight. Only the digits after the decimal point. For example, 0.1 indicates 1/2 = 0.5, 0.01 indicates 1/4 = 0.25, and 0.11 indicates 1/2 + 1/4 = 0.75, at last, we can only extend the number to infinitely close to 0.1. If you want to learn more about this, you can read the book "understanding computer systems in depth. The suggestion provided by Bloch is to use the bigdecimal class in Java to handle precise floating point computation. It is interesting to see that bigdecimal (char [] In, int offset, int Len) is very interesting. This method converts a string to a floating point. I think this code is worth learning, in the past, there were similar examples During Microsoft interviews.

 

Puzzle 3 long division
Public class Longdivision {public static void main (string [] ARGs) {final long micros_per_day = 24*60*60*1000*1000; final long millis_per_day = 24x60x60*1000; system. out. println (micros_per_day/millis_per_day );}}

The first micros_per_day will overflow and should not be confused by the previous long. This long will only be used after the expression is computed, but in the whole expression calculation, every constant is an int, and the whole process is calculated according to the int type. Of course, this space is not enough. This mistake is often easy to make.

 

Puzzle 4 primary problems
 
Public class elementary {public static void main (string [] ARGs) {system. Out. println (12345 + 5432l );}}

This problem is really too painful. First, the printed result is definitely not the sum of the two decimal digits you look at, but the second addition is actually 5432, followed by the letter l ....... this is an error caused by code writing, so long should be capitalized in the future, OK?

 

Interesting things about puzzle 5 hexadecimal
Public class joyofhex {public static void main (string [] ARGs) {system. Out. println (long. tohexstring (0x00000000l + 0 xcafebabe ));}}

It is also a simple addition. Most people think that the result is 0x1cafebabel, but it is worth noting that the addition number on the right is a hexadecimal integer, And the hexadecimal constant is signed, that is, if the highest bit is set, it indicates a negative number. Therefore, 0xcafebabe is a negative number, which must be expanded first when adding, so that it becomes 0 xffffffffcafebabe.

 

Puzzle 6 Multiple conversions
 
Public class multicast {public static void main (string [] ARGs) {system. Out. println (INT) (char) (byte)-1 );}}

In this example, the integer-1 is converted in multiple ways and finally printed out? First, let's take a look at the three data types of placeholder int 32 char 16 byte8. Then, according to the conversion sequence, we can see that we need to first truncate the 32-bit-1 to eight bits, then expand to 16 bits, and then to 32 bits. First,-1 is represented by a binary complement, that is, 1111... 1. Keep the last 8 digits, or-1. char is unsigned, which becomes 65535. at this time, char is expanded to a signed int, and the front is still filled with zero, so we can see that it is 65535.

The book provides a good suggestion. When symbol extension is involved, it can be used with a wide data type phase, such as byte conversion to Char, if you do not want symbol extension, you can use the following operations:

Char c = (char) (B & 0xff); in this way, there will be no symbol extension. I believe everyone understands the truth.

 

Puzzle 7 swap content
 
Public class cleverswap {public static void main (string [] ARGs) {int x = 1984; int y = 2001; x ^ = y ^ = x ^ = y; system. out. println ("x =" + x + "; y =" + Y );}}

I don't like this code very much, but it is poorly written. I guess it will be written only when I want to explain an example. First of all, the background is that I think we all know that a small tip means that we do not use a temporary variable to exchange two numbers. There are two basic methods: A = a + B; B = A-B; A = A-B; and A = a ^ B; B = a ^ B; A = a ^ B; the latter is quite famous. It uses a number that is different from itself or 0, while any number and 0 are different or self. So there is the previous method .. Of course, the above Code cannot produce correct results. Bloch breaks down x ^ = y ^ = x ^ = Y in the above Code. I think it is clear: first, let's clarify two points, one is to evaluate the operator from left to right, and the other is to take the value of X first, then evaluate x ^ y, and then assign the value to X.

So the above operations are as follows (from the original article in the book ):

Puzzle 8 Dos Equis
Public class dosequis {public static void main (string [] ARGs) {char x = 'X'; int I = 0; system. Out. Print (true? X: 0); system. Out. Print (false? I: X );}}

I indicated that I had not found any problems after staring at this expression for a long time, because I only? Condition X: Y is regarded as a control structure, while ignoring this is actually an expression. The expression is characterized by a value. What is the value type? I believe that the problem can be found here. This is actually a mixed type calculation. The two data types left and right of the colon are inconsistent. The following rule is introduced:

    • If the second and third operands have the same type, it is the type of the conditional expression. In other words, you can avoid great troubles by bypassing the computation of the hybrid type.
    • If the type of an operand is t, t indicates byte, short, or char, And the other operand is a constant expression of the int type, its value can be represented by the type T, then

The expression type is T.

    • Otherwise, binary numbers are used to increase the operand type, and the conditional expression type is the type after the second and third operands are upgraded.

Therefore, in the second expression, I is a variable, So X is promoted to an int. With this result, the puzzle is very good.

 

Puzzle 9 half a catty Puzzl 10 eight two
Public class Tweedledum {public static void main (string [] ARGs) {// put your declarations for X and I here x + = I; // must be legal x = x + I; // must be illegal }}

In this example, I talked about it yesterday when I was eating with my roommate, Raytheon. Two interesting puzzle files were written together, asking for the Statement of x and I. The first one is that X + = I is required, X = x + I is invalid. I still remember that it is related to the width and width of the data type, that is, you cannot assign a wide data type to a data type that is narrower than the data type. So if X is short and I is int, the second one is invalid. Now let's see why the compound assignment expression is legal .. Java design. "Compound value assignment expressions automatically convert the calculation results they execute to the type of the variable on the left." In this case, if the left side is narrower, It is implicitly truncated. Therefore, compound assignment expressions are dangerous!

Let's look at another one or two. I didn't think that makes X + = I invalid, and X = x + I legal. The knowledge point here is that the composite value assignment operator applies only to basic types or encapsulates classes of basic types, such as integer. Except for string, if the left side is string, the right side can be of any type. This is an example that makes X + = I invalid, that is, defining X as an object is OK. In the value assignment operation, an object can point to another type as a reference. So the method is that X is the object and I is the string.

 

The above are the 10 puzzle of Chapter 2, which is mainly related to the expression value. The conversion between different wide and narrow data types is involved multiple times, data Type placeholder does not cause some trouble for development, but it seems to have some value for efficiency. I dare not say this too much. I remember some books wrote that float should not be used as far as possible, because his efficiency is not much higher than double, but the latter is more accurate. Secondly, it involves some traps that may be easily caused by special expressions. Although it feels a little too detailed, it can help us broaden our horizons, at least not to debug bugs in the future.

The next chapter is the character puzzle, which is the most interesting topic today.

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.