Friday, April 15, 2011

Java Integer Arithmetic For Beginners_4389


Java Integer Arithmetic For Beginners Integer arithmetic expressions in Java
In Java, integer arithmetic is performed using "integer data types".In Java Data Types, we discussed some of these types—byte, short, int and long—and gave examples of "integer constants". An integer constant (e.g. 23, 0, -245) is the simplest example of an integer expression. However, most of the time, we write integer expressions by combining constants and variables with the following arithmetic operators:
For example, suppose we have the following declaration:
int a, b, c;
then the following are all valid expressions:
a + 39
a + b - c * 2
b % 10 //the remainder when b is divided by 10
c + (a * 2 + b * 2) / 2
The operators +, - and * all give the expected results. However, / performs integer division; if there is any remainder, it is thrown away. We say integer division truncates. Thus 19 / 5 gives the value 3; the remainder 4 is discarded.
But what is the value of -19 / 5? The answer here is –3. The rule is that, in Java, integer division truncates towards zero. Since the exact value of –19 ÷ 5 is –3.8, truncating towards zero gives –3.
The % operator gives the remainder when one integer is divided by another; for example,
19 % 5 evaluates to 4;
j % 7 gives the remainder when j is divided by 7;

No comments:

Post a Comment