Arithmetic expressions and operators
Learn how to compute expressions in Java, and how to convert between different types of data using casting. Be careful of the difference between integer and floating-point division!
We'll cover the following...
Computing values in Java works much like you’d expect from most other languages:
class ExpressionOperand {public static void main(String args[]) {int x;x = (3 * 6) + 24;System.out.println(x);}}
There are two things to be aware of:
-
Like in C or C++, but unlike Javascript or Python3, division of two integers yields an integer.
-
Operators given two different types (like
2 + 1.7
) promote, or automatically convert, the more limited type.2
will be converted to the floating point2.0
, and the resulting value will be a floating point that must be stored in a variable of typefloat
ordouble
.
Integer and floating point division
There are two types of division, and each is sometimes useful. Integer division takes two integers and evaluates to an integer. Floating-point division takes two floating-point numbers (numbers with a decimal point) and evaluates to a floating-point number.
Let’s say I have 18 cents and 5 nieces. How ...