Skip to content

Operators and expressions ​

Arithmetic operators ​

Java provides several arithmetic operators that let you perform mathematical calculations.

SymbolNameDescription
+AdditionAdds two values
-SubtractionFinds the difference between two values
*MultiplicationMultiplies two values
/DivisionDivides one value by another
%RemainderCalculates the remainder on division

Expressions ​

An expression in Java is a collection of operators and variables that evaluates to a single value.

java
public class Main {
    public static void main(String[] args) {
        int bookPrice = 15; // variable
        int numberOfBooks = 100; // variable
        int totalValue = bookPrice * numberOfBooks; // expression

        System.out.println(totalValue);
    }
}
1500

INFO

int in Java is an integer, whereas double is used for decimal numbers.

Exponentiation ​

There is no exponentiation operator in Java. Instead, you use Math.pow.

java
public class Main {
  public static void main(String[] args) {
    double result = Math.pow(2, 3);
    System.out.println(result);
  }
}
8.0

Modifying a Variable ​

When updating a variable, we can use its old value to calculate its new value.

java
public class Main {
    public static void main(String[] args) {
        int availableBooks = 120;
        availableBooks = availableBooks + 10;

        System.out.println(availableBooks);
    }
}
130

We can do this a bit more quickly with += and -=.

java
public class Main {
    public static void main(String[] args) {
        int availableBooks = 120;

        availableBooks += 10;
        System.out.println(availableBooks);

        availableBooks -= 5;
        System.out.println(availableBooks);
    }
}
130
125