Module 2: Java Fundamentals
Operators in Java
Use arithmetic, comparison, logical, and assignment operators.
Operators combine values, compare values, or update variables. Understanding the result type and operator precedence helps prevent confusing expressions.
Arithmetic operators#
int a = 10;
int b = 3;
System.out.println(a + b); // 13
System.out.println(a - b); // 7
System.out.println(a * b); // 30
System.out.println(a / b); // 3
System.out.println(a % b); // 1
When both operands are integers, / performs integer division, so 10 / 3 is 3, not 3.333.... Use a floating-point operand if you need a decimal result.
Comparison operators#
==, !=, >, <, >=, and <= compare values and produce a boolean result. For object references such as strings, == compares whether the references identify the same object; use .equals() when checking string content.
int age = 20;
System.out.println(age >= 18); // true
Logical operators#
&&means AND: both conditions must be true.||means OR: at least one condition must be true.!reverses a boolean value.
The && and || operators short-circuit, which means Java may skip evaluating the right-hand side when the result is already known.
Assignment and increment#
int points = 5;
points += 2; // points is now 7
points++; // points is now 8
Precedence and readability#
Multiplication usually happens before addition, but parentheses make intent clearer:
int result = (2 + 3) * 4; // 20
Prefer small, readable expressions over relying on readers to remember a complicated precedence chain.
Practice#
Create two integer variables and print their sum, difference, product, quotient, and remainder. Try the quotient again after casting one operand to double.