An arithmetic expression is an expression that results in a numeric value. There are two kinds of numeric values, integers (whole numbers), and real or floating point numbers (numbers containing a decimal point).
The simplest arithmetic expressions are literals (the number itself, written with digits) and variables (named values):
A literal integer, representing the number 12.
A literal integer, representing the number negative 5.
A literal real, representing the number negative 5.
A literal real, representing the number 50000.
A variable. If it was declared as
, it will hold an integer value; but if declared as
, it will hold a real value.
More complex arithmetic expressions can be formed by connecting literals and variables with one of the arithmetic operators:
Multiply (it's difficult to type the usual multiplication symbol).
Divide (it's difficult to type the usual division symbol).
Division of two integer values will give an integer result (any fractional part is just discarded). For example,
2. This is called integer division.
Used for integers only, this operation gives the remainder of a division; for example,
4. The sign (positive or negative) of the result is the same as the sign of the first number.
Parentheses may be used to control the order in which the operators are applied. If you don't use parentheses, operations with higher precedence are done first.
int i=5.0are illegal. This is to protect you from accidentally losing the fractional part.However, if you use a cast to reassure Java that you really mean it, then it's legal. For example,
is legal,and gives
double. However, there are other numeric primitive types.