Free Ebook cover Java for Beginners: A Complete Introduction to Programming with Java

Java for Beginners: A Complete Introduction to Programming with Java

New course

10 pages

Operators and Expressions for Java Calculations

CapĂ­tulo 3

Estimated reading time: 5 minutes

+ Exercise

What Operators and Expressions Are

An operator is a symbol that performs a calculation or a test (for example + or >). An expression is a piece of code that produces a value (for example price * quantity or total >= 100). You will often build programs by composing small expressions and checking their results.

Arithmetic Operators for Calculations

Arithmetic operators work with numbers to compute totals, differences, and more.

  • + addition
  • - subtraction
  • * multiplication
  • / division
  • % remainder (modulo)

Compute a Line Total and a Cart Total

Start with small, testable expressions. Compute a line total (unit price times quantity), then add it to a cart total.

double unitPrice = 19.99; int quantity = 3; double lineTotal = unitPrice * quantity; double shipping = 4.99; double cartTotal = lineTotal + shipping; System.out.println(lineTotal); System.out.println(cartTotal);

Division and Remainder: Splitting Items Evenly

Integer division drops the fractional part. The remainder operator tells you what is left over.

int items = 10; int people = 3; int eachGets = items / people; int leftover = items % people; System.out.println(eachGets);   // 3 System.out.println(leftover);   // 1

If you need a fractional result, make sure at least one operand is a floating-point number.

Continue in our app.

You can listen to the audiobook with the screen off, receive a free certificate for this course, and also have access to 5,000 other free online courses.

Or continue reading below...
Download App

Download the app

int items = 10; int people = 3; double eachGets = (double) items / people; System.out.println(eachGets); // 3.3333333333333335

Assignment and Compound Assignment

The assignment operator = stores the value of an expression into a variable. Compound assignment operators combine an operation with assignment, which is common when updating totals.

  • += add and assign
  • -= subtract and assign
  • *= multiply and assign
  • /= divide and assign
  • %= remainder and assign

Step-by-Step: Build a Running Total

Imagine a checkout where you add items one by one and then apply a discount.

double total = 0.0; total += 12.50;   // add first item total += 7.25;    // add second item total += 3.99;    // add third item System.out.println(total);

Now apply a discount amount (not a percentage yet).

double discountAmount = 5.00; total -= discountAmount; System.out.println(total);

Apply a Percentage Discount

A percentage discount is usually computed as total * rate, then subtracted.

double total = 80.00; double discountRate = 0.15; double discount = total * discountRate; total -= discount; System.out.println(total); // 68.0

You can also write it as a single expression:

double total = 80.00; total *= (1 - 0.15); System.out.println(total); // 68.0

Increment and Decrement (++, --)

++ increases a number by 1, and -- decreases it by 1. They are often used for counters.

Prefix vs Postfix

The position matters when the operator is used inside a larger expression.

  • Postfix x++: use the current value, then increment.
  • Prefix ++x: increment first, then use the new value.
int x = 5; System.out.println(x++); // prints 5, x becomes 6 System.out.println(x);   // prints 6 int y = 5; System.out.println(++y); // y becomes 6, prints 6

Practical Example: Counting Items Scanned

int scanned = 0; scanned++; scanned++; System.out.println(scanned); // 2

Comparison Operators (Producing true/false)

Comparison operators produce a boolean result: true or false. These are essential for checking conditions like eligibility for free shipping or whether a discount applies.

  • > greater than
  • >= greater than or equal
  • < less than
  • <= less than or equal
  • == equal to
  • != not equal to

Examples: Free Shipping and Minimum Order Checks

double total = 68.00; boolean freeShipping = total >= 50.00; System.out.println(freeShipping); // true int age = 17; boolean canBuy = age >= 18; System.out.println(canBuy); // false

Be careful not to confuse = (assignment) with == (comparison).

Logical Operators (Combining Conditions)

Logical operators combine boolean expressions into larger rules.

  • && AND: true only if both sides are true
  • || OR: true if at least one side is true
  • ! NOT: flips true to false and false to true

Examples: Discount Rules

Example rule: apply a discount if the customer is a member AND the total is at least 100.

boolean isMember = true; double total = 120.00; boolean discountApplies = isMember && total >= 100.00; System.out.println(discountApplies); // true

Example rule: allow checkout if the cart is not empty OR the user is using a gift card (simplified).

int itemCount = 0; boolean hasGiftCard = true; boolean canCheckout = itemCount > 0 || hasGiftCard; System.out.println(canCheckout); // true

Short-Circuit Behavior

&& and || are short-circuit operators: Java may skip evaluating the right side if the left side already determines the result. This is useful for safe checks.

int quantity = 0; boolean valid = quantity != 0 && (100 / quantity) > 1; System.out.println(valid); // false, and no division happens

Operator Precedence: Which Parts Run First

When an expression has multiple operators, Java follows precedence rules (a priority order). A simplified view that covers most beginner cases is:

  • Parentheses ( )
  • Unary operators like ++, --, !
  • Multiplication/division/remainder: *, /, %
  • Addition/subtraction: +, -
  • Comparisons: >, >=, <, <=
  • Equality: ==, !=
  • Logical AND: &&
  • Logical OR: ||
  • Assignment: =, +=, -=, ...

Example: Total With Tax and Shipping

Without parentheses, multiplication happens before addition.

double subtotal = 50.00; double taxRate = 0.10; double shipping = 5.00; double total = subtotal + subtotal * taxRate + shipping; System.out.println(total); // 60.0

This is equivalent to:

double total = subtotal + (subtotal * taxRate) + shipping;

How Parentheses Change Results

Parentheses force a different grouping.

int a = 10; int b = 4; System.out.println(a - b * 2);     // 2 (because b*2 happens first) System.out.println((a - b) * 2);   // 12 (because a-b happens first)

Precedence With Logical and Comparison Operators

Comparisons happen before logical operators, so this reads naturally.

int age = 20; boolean isStudent = false; boolean eligible = age >= 18 && !isStudent; System.out.println(eligible); // true

If you want to make intent extra clear, add parentheses even when they are not required.

boolean eligible = (age >= 18) && (!isStudent);

Mini Practice: Predict the Output (Then Run)

For each task, write down what you think will print before running the code. Then run it and compare.

Task 1: Arithmetic and Precedence

int result1 = 8 + 2 * 5; int result2 = (8 + 2) * 5; System.out.println(result1); System.out.println(result2);

Task 2: Compound Assignment

double total = 40.0; total += 10.0; total *= 0.9; System.out.println(total);

Task 3: Postfix vs Prefix

int x = 3; int y = x++ + 5; System.out.println(x); System.out.println(y);

Task 4: Comparisons and Logical Operators

double total = 99.99; boolean isMember = true; boolean getsDiscount = isMember && total >= 100.0; System.out.println(getsDiscount);

Task 5: Short-Circuit Safety

int quantity = 0; boolean ok = quantity > 0 && (50 / quantity) > 1; System.out.println(ok);

Task 6: Remainder in Real Scenarios

int candies = 23; int bags = 5; int perBag = candies / bags; int extra = candies % bags; System.out.println(perBag); System.out.println(extra);

Now answer the exercise about the content:

Why might you cast one operand to double before dividing two integers in Java (for example, (double) items / people)?

You are right! Congratulations, now go to the next page

You missed! Try again.

When both operands are integers, division uses integer division and truncates the fractional part. Casting one operand to double makes the calculation use floating-point division, producing a decimal result.

Next chapter

Working with Input and Output in Java Console Programs

Arrow Right Icon
Download the app to earn free Certification and listen to the courses in the background, even with the screen off.