Professional Documents
Culture Documents
When you use arithmetic, bitwise, or shift operators in code, the Java compiler automatically performs any necessary widening conversions before completing the operations these are known as arithmetic promotions. Because of these arithmetic promotions, the results of these operations are always at least of type int.
conversions are carried out automatically. However, you can cast widening conversions explicitly in order to make your code more readable. You cast a conversion by preceding a value with the name of the new data type in parentheses. For example, in this code you precede the variable a with (byte) to convert the int to a byte: When converting an int to a byte, the compiler discards all but the last eight bits of the number. In this case, 1 0000 0001 (257) becomes 00000001 (1), so the value of b is 1. You need to take care when performing narrowing conversions because it is possible to lose or radically alter data when you do so. Consider the following code: short a = -4;short b = 1; short c = (short)(a >>> b); In this case, because the first operand in the expression is a short, it is automatically converted to an int for the operation to be performed. So the bit pattern of the short(1111 1111 1111 1100) 16 bits, becomes 1111 1111 1111 1111 1111 1111 1111 1100 32 bits. And because the operator is the unsigned right shift operator, the new bit is set to 0. This results in a bit pattern of 0111 1111 1111 1111 1111 1111 1111 1110, even though the operand is a negative number. However, when the result is cast back to a short, the new bit is lost and the leftmost bit of the short is set to 1. The result of the operation is a negative number just as if you had used the signed right shift operator (>>). So in this example, the original result, 0111 1111 1111 1111 1111 1111 1111 1110, is cast to short as 1111 1111 1111 1110.
Summary
Primitive data types can be converted from one type to another when you assign a value to a variable, when you pass a value to a method, or when using an arithmetic expression. In arithmetic expressions, conversion is known as arithmetic promotion. Promotion follows a number of rules, depending on the type of the operands in the expression and whether the operator is binary or unary. The Java compiler performs widening conversions that is, where the new data type can accept a wider range of values than the old data type automatically. You can explicitly instruct Java to convert a value using casting. You do this by preceding the value you want to convert with the new data type in parentheses. Casting allows you to perform narrowing conversions, which are otherwise illegal in Java. However, you should be careful when performing these conversions because they can result in meaningless or unexpected values.