Search⌘ K
AI Features

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:

Java
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:

  1. Like in C or C++, but unlike Javascript or Python3, division of two integers yields an integer.

  2. Operators given two different types (like 2 + 1.7) promote, or automatically convert, the more limited type. 2 will be converted to the floating point 2.0, and the resulting value will be a floating point that must be stored in a variable of type float or double.

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 = ...