Arithmetic expressions and operators
Explore how to use arithmetic expressions and operators in Java. Understand integer and floating-point division, the role of casting between data types, and how combined assignment and increment operators simplify your code. This lesson clarifies key concepts needed for accurate computations and control of numerical values in Java programming.
We'll cover the following...
Computing values in Java works much like you’d expect from most other languages:
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.2will be converted to the floating point2.0, and the resulting value will be a floating point that must be stored in a variable of typefloatordouble.
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 much money should I give to each? With floating point division, 18/5 = ...