Arithmetic operators
The five arithmetical operations supported by the Java language are:
+ addition
- subtraction
* multiplication
/ division
% modulo
Operations of addition, subtraction, multiplication and division literally correspond with their respective mathematical operators.
The only one that you might not be so used to see may be modulo; whose operator is the percentage sign (%). Modulo is the operation that gives the remainder of a division of two values. For example, if we write:
a = 10 % 3;
the variable a will contain the value 2, since 1 is the remainder from dividing 10 between 3.
compound assignment
When we want to modify the value of a variable by performing an operation on the value currently stored in that variable we can use compound assignment operators:
expression is equivalent to
value += increase; value = value + increase;
a -= 5; a = a - 5;
a /= b; a = a / b;
price *= units + 1; price = price * (units + 1);
and the same for all other operators.
For example:
import java.io.*;
public class arithmeticOperator
public static void main (String args[])
{
int a, b=3;
a = b;
a+=2; // equivalent to a=a+2
System.out.println( a);
}
No comments:
Post a Comment