VisualStudioTutor.com Java Tutorial All Lessons

Lesson 8 of 20

Operators and Expressions

Perform arithmetic, comparisons, assignments, and logical operations, and understand operator precedence.

Learning objectives

  • Use arithmetic operators in calculations.
  • Compare values with relational operators.
  • Combine conditions using logical operators.
  • Use compound assignment and increment/decrement operators.
  • Control evaluation order with parentheses.

1. Arithmetic operators

Java supports addition +, subtraction -, multiplication *, division /, and remainder %.

Example: arithmetic

public class ArithmeticDemo {
    public static void main(String[] args) {
        int a = 17;
        int b = 5;

        System.out.println("a + b = " + (a + b));
        System.out.println("a - b = " + (a - b));
        System.out.println("a * b = " + (a * b));
        System.out.println("a / b = " + (a / b));
        System.out.println("a % b = " + (a % b));
    }
}

Because both operands in a / b are integers, the result is integer division: 3, not 3.4.

2. Relational operators

Comparisons return a Boolean result.

int score = 72;

System.out.println(score >= 50); // true
System.out.println(score == 100); // false
System.out.println(score != 0);   // true

3. Logical operators

Use && for logical AND, || for logical OR, and ! for NOT.

Example: eligibility rule

int age = 20;
boolean hasLicense = true;

boolean canRent = age >= 18 && hasLicense;
System.out.println("Can rent: " + canRent);

4. Assignment and increment

int points = 10;
points += 5; // same as points = points + 5
points++;    // add 1
System.out.println(points); // 16

5. Operator precedence

Multiplication and division are evaluated before addition and subtraction. Parentheses make the intended order explicit.

double result1 = 10 + 5 * 2;     // 20
double result2 = (10 + 5) * 2;   // 30

Mini project: BMI calculator

public class BmiCalculator {
    public static void main(String[] args) {
        double weightKg = 70.0;
        double heightM = 1.75;

        double bmi = weightKg / (heightM * heightM);
        boolean healthyRange = bmi >= 18.5 && bmi < 25.0;

        System.out.printf("BMI: %.2f%n", bmi);
        System.out.println("In standard healthy range: " + healthyRange);
    }
}

Common mistakes

ProblemWhy it happensHow to fix it
Using = when comparing values= assigns; it does not compare.Use == for primitive-value equality.
Unexpected integer divisionBoth operands are integers.Use at least one decimal operand, e.g. 17.0 / 5.
Complex Boolean expression is hard to readToo many operators are combined.Use parentheses and intermediate Boolean variables.

Summary

Operators turn stored values into useful expressions. In Lesson 9, you will use Boolean expressions to make decisions with if, else, and switch.