Java Reference
In-Depth Information
// Ok. 20 * 6 will be replaced by 120
// b2 = 120 is ok, because 120 is in the range -128 and 127
b2 = 20 * 6;
// An error. i2 * 12 is of the type int. int to byte assignment is not allowed.
b2 = i2 * 12;
b2 = (byte)(i2 * 12); // OK
// Ok. i2 * b2 is of the type int and int to float assignment is allowed
f2 = i2 * b2;
// Error. d2 * i2 is of type double and double to float assignment is not allowed
f2 = d2 * i2;
f2 = (float)(d2 * i2); // Ok
Division Operator (/)
The division operator (/) is used in the form
operand1 / operand2
The division operator is used to compute the quotient of two numbers, for example 5.0/2.0 results in 2.5 . All the
rules I discussed about the numeric data conversion of the operands and the determination of the data type of the
expression involving the addition operator are also valid for an expression involving the division operator.
There are two types of division:
Integer division
Floating-point division
If both the operands of the division operator are integers, that is, byte , short , char , int , or long , the usual
division operation is carried out and the result is truncated towards zero to represent an integer. For example, if you
write an expression 5/2 , the division yields 2.5; the fractional part 0.5 is ignored; and the result is 2 . The following
examples illustrate the integer division:
int num;
num = 5/2; // Assigns 2 to num
num = 5/3; // Assigns 1 to num
num = 5/4; // Assigns 1 to num
num = 5/5; // Assigns 1 to num
num = 5/6; // Assigns 0 to num
num = 5/7; // Assigns 0 to num
In all of the above examples, the value assigned to the variable num is an integer. The result is an integer in all
cases not because the data type of variable num is int . The result is integer because both the operands of the division
operator are integers. Because the data types of both operands are int , the whole expression 5/3 is of type int .
Because the fractional portion (e.g. 0.5, 0.034) cannot be stored in an int data type, the fractional portion is ignored
 
Search WWH ::




Custom Search