# Java puzzles (1)

Source: Internet
Author: User
Puzzle 1, odd
`public static boolean isOdd(int i ){    return i%2==1;}`

When I is a negative odd number, I % 2 is equal to-1 instead of 1. Therefore, the isOdd method returns false incorrectly. To prevent this, test whether your method performs correctly when passing negative, zero, and positive values to each numeric parameter.

This problem can be easily corrected. Just compare I % 2 with 0 instead of 1, and reverse the meaning of the comparison:

`public static boolean isOdd(int i){ return i % 2 != 0; } `

If you are using the isOdd method in a performance-critical environment, it will be better to replace the AND (&) operator with the bitwise OPERATOR:

`public static boolean isOdd(int i){ return (i & 1) != 0;} `
Puzzle 2: The floating point number is not accurate at the time of change. Only the int or BigDecimal type can be used for monetary computation. (Also separately) puzzle 3, long integer
`public class LongDivision{ public static void main(String args[]){ final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000; final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;     System.out.println(MICROS_PER_DAY/MILLIS_PER_DAY);      }}`

We plan to print 1000. Unfortunately, it prints 5. What happened here?
The problem is that the computation of the constant MICROS_PER_DAY "indeed" overflows. Although the calculation result is suitable for putting in long and its space is surplus, this result is not suitable for putting in int. This computation is completely performed using the int operation, and the result is promoted to long only after the computation is completed. It is too late: the computation has exceeded, it returns a value smaller than 200 times. Increasing from int to long is a type of widening original type conversion (widening primitive conversion), which retains (incorrect) values. This value is then divisible by MILLIS_PER_DAY, and the calculation of MILLIS_PER_DAY is correct because it is suitable for int operations. In this way, the division result is 5.

So why is the calculation performed using the int operation? Because all the factors that multiply together are int values. When you multiply two int values, you get another int value. Java does not have a category

This is a linguistic feature. It means that the type of the variable storing the result affects the type used by calculation.

By using long constants to replace int constants as the first factor of each product, we can easily correct this program. In this way, all subsequent computations in the expression can be forced to use the long operation.

. Although this is only required in the MICROS_PER_DAY expression, it is a good way to do so in both products. Similarly, using long as the product's "first" value is not always necessary, but it is also a good form. In both calculations, the lon value can be used to clearly indicate that they do not overflow. The following program will print out the expected 1000:

`public class LongDivision{ public static void main(String args[ ]){ final long MICROS_PER_DAY = 24L * 60 * 60 * 1000 * 1000; final long MILLIS_PER_DAY = 24L * 60 * 60 * 1000;     System.out.println(MICROS_PER_DAY/MILLIS_PER_DAY);   } }`

The lesson is simple: when you are operating on a large number, be sure to guard against overflow-it is a silent killer. Even if the variable used to save the result is large enough, it does not mean that the calculation of the result is of the correct type. If you are not sure, use the long operation to execute the entire computation.

Question 4
`public class Elementary{ public static void main(String[] args){     System.out.println(12345+5432l);   } } `

`System.out.println(12345+5432L); `

Note the differences between 1 and L (l). puzzles 5, hexadecimal interesting things

`public class JoyOfHex{ public static void main(String[] args){     System.out.println(       Long.toHexString(0x100000000L + 0xcafebabe));   } } `

The hexadecimal highest bit is set to a negative number. Puzzle 6: Multiple Transformations
`public class Multicast{ public static void main (String[] args){     System.out.println((int)(char)(byte) -1);   } } `

Symbol extension rules when a narrow integer is converted to a wider INTEGER: if the initial value type is signed, the extension is executed (that is, if the symbol bit

If it is 1, it is extended to 1. If it is zero, it is extended to 0). If it is char, no matter what type it will be upgraded to, it will execute zero extension.

After learning about the above rules, let's take a look at the question: Because byte is a signed type, we are raising the byte value-1 (Binary: 11111111)

When it is upgraded to char, the symbol bit is extended, and the symbol bit is 1, so we add 8 1 s, and finally 16 1 S. Then, when we upgrade from char to int

The char type is upgraded to other types. Therefore, the int value is 65535 instead of the symbol extension.

If a char value c is transformed into a type with a wider width, it is only expanded with zero, but if it clearly expresses the intention to expand with zero, you can consider

Java code

2 int I = c & 0 xffff; // essentially equivalent to: int I = c;

If you want to convert a char value c to an integer with a wider width and a signed extension, convert the char to a short

Char has the same width, but it is signed:

Java code

3 int I = (short) c;

If you want to convert a byte value B to a char without symbolic extension, you must use a single bit mask to limit it:

Java code

4 char c = (char) (B & 0xff); // char c = (char) B; For signed Extension

`System.out.println(12345+5432L); `

Related Keywords:
Related Article

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.