Operators and Expressions
Explore how to build and use expressions in Java with arithmetic, relational, logical, and bitwise operators. Understand operator precedence and apply these tools to write effective code that transforms data into actionable logic.
To build useful software, we need to transform, compare, and make decisions based on the data. Operators are the verbs of programming. They allow us to act on our variables. Whether we are calculating the trajectory of a spacecraft, checking if a user’s password is correct, or determining if a game character has enough health to survive an attack, we rely on operators to construct the logic.
What is an expression?
Previously, we wrote code like this:
int age = 25;
We called 25 a literal, but it is also the simplest form of an expression. In Java, an expression is any piece of code that evaluates to a single value. When Java sees 25, it evaluates it to the integer 25.
But expressions can be much more powerful. We can modify that value by adding operators.
age = 25 + 1;
Here, 25 + 1 is an expression. The + operator tells Java to perform an action such as addition and produce a new value, 26, which is then assigned to the variable.
In this lesson, we will move beyond simple literals and learn how to build complex expressions using mathematical, relational, and logical operators.
Arithmetic operators
Java uses standard arithmetic operators for mathematical calculations:
addition (
+)subtraction (
-)multiplication (
*)division (
/)
These work almost exactly as they do in basic algebra. However, there is one critical behavior to watch for integer division. When we divide two integers in Java (e.g., 5 / 2), the result is truncated to an integer (2), not a decimal (2.5). To get a decimal result, at least one operand must be a floating-point number (e.g., 5.0 / 2).
We also have the modulus operator (%), which returns the remainder of a division. This is extremely useful for tasks like determining if a number is even or odd (checking if number % 2 is 0).
Lines 7–8: We calculate area and perimeter using standard multiplication (
*) and addition (+).Line 16: We divide
13by4. Since both are integers, the result is truncated to3.Line 17: We use the modulus operator (
%) to find the remainder (1) after division. ... ...