Skip to content

Operators for Calculation#

Operators let you do various things with variables.

Typical Mathematical Operators#

We have used these already in all of the examples without formally introducing them, but here are the common mathematical operators you already know:

  • + and - add/subtract two things
  • * and / multiply/divide two things
  • % is one you may remember from primary school. This is the remainder of a division. 7 % 3 would result in 1. This operator comes up whenever you need to do alternating stripes or need to work out stuff surrounding date and time manually. The operator itself is called the "modulo" operator.

Assignment#

As mentioned earlier, = is not actually the mathematical equals sign, but an assignment operator.

Short Forms#

When dealing with numbers, there are a lot of specialized operators that you might come across:

  • Adding something to a variable would usually be totalCalories = totalCalories + intake, but it can also be written as totalCalories += intake.
  • Subtracting something would be creditsInWallet = creditsInWallet - itemPrice or can be abbreviated as creditsInWallet -= itemPrice.
  • These also exist for multiplication, where width = width * scaleFactor becomes width *= scaleFactor.
  • I don't have a great example for division, but I bet you already know how this works by now.

VERY Short Forms for Increment/Decrement#

We'll be doing a LOT of counting variables up and down. And this is quite common in programming in general, that's why pretty much all languages have even shorter versions for incrementing or decrementing a variable. Let's say we have an integer variable called counter. We can then write any of these:

  • counter++ (post-increment) will return its current value and then add one to that current value
  • counter-- (post-decrement) will return its current value and then subtract one from that current value
  • ++counter (pre-increment) adds one to the current value of the variable and then return the new value
  • --counter (pre-decrement) subtracts one from the current value of the variable and then return the new value

These are especially useful in loops.

Further Details#

There are even more operators in Java, and they also come with additional rules, like their precedence. If you're interested in this topic, Please take a look at the Java Tutorials page about Operators

Relevant excerpt from Learning Processing#

(the section starts at 1:48:56 and runs through 1:53:20, the video should start and stop on these automatically.)