Arithmetic OperatorsS2C Home « Arithmetic Operators

Symbols used for mathematical and logical manipulation that are recognized by the compiler are commonly known as operators in Java. In the first of five lessons on operators we look at the arithmetic operators available in Java.

Arithmetic Operators Overview Top

We are familiar with most of the arithmetic operators in the table below from everyday life and they generally work in the same way in Java. The arithmetic operators work with all the Java numeric primitive types and can also be applied to the char primitive type.

Operator Meaning Example Result Notes
+Additionint b = 5; b = b + 5;10
-Subtractionint b = 5; b = b - 5;0
/Divisionint b = 7; b = 22 / b;3When used with an integer type, any remainder will be truncated.
*Multiplicationint b = 5; b = b * 5;25
%Modulusint b = 5; b = b % 2;1Holds the remainder value of a division.
++Incrementint b = 5; b++;6See below.
--Decrementint b = 5; b--;4See below.

Increment And Decrement Operators

Both these operators can be prepended (prefix) or appended (postfix) to the operand they are used with. When applied to an operand as part of a singular expression it makes no difference whether the increment and decrement operators are applied as a prefix or postfix. With larger expressions however, when an increment or decrement operator precedes its operand, Java will perform the increment or decrement operation prior to obtaining the operand's value for use by the rest of the expression. When an increment or decrement operator follows its operand, Java will perform the increment or decrement operation after obtaining the operand's value for use by the rest of the expression. Lets look at some code to illustrate how this works:


package info.java8;
/*
  Increment And Decrement Operators
*/ 
public class IncDec {

    public static void main (String[] args) {
        byte a = 5;
        byte b = 5;
        // Singular Expressions
        a++;
        ++b;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        // Larger Expressions
        a = 1;
        b = a++;
        System.out.println("b using a postfix = " + b);
        a = 1;
        b = ++a;
        System.out.println("b using a prefix = " + b);
    }
}

Running the IncDec class produces the following output:

run incdec
Screenshot 1. Running the IncDec class.

As you can see with the last two lines of output, the postfix increment is applied after the expression is evaluated, whereas the prefix increment is applied before.

Related Quiz

Fundamentals Quiz 6 - Arithmetic Operators Quiz

Lesson 7 Complete

In this lesson we looked at the arithmetic operators used in Java.

What's Next?

In the next lesson we look at the relational & logical operators used in Java.