Java - Operator Arithmetic Operators

What are Arithmetic Operators?

The following table lists all arithmetic operators in Java.

All operators listed in Table can only be used with numeric type operands.

Operators DescriptionType Usage Result
+ Addition Binary2 + 5 7
- SubtractionBinary5 - 2 3
+ Unary plus Unary +5 Positive five. Same as 5
- Unary minusUnary -5 Negative of five
* Multiplication Binary5 * 3 15
/ Division Binary5 / 2 2
% ModulusBinary5 % 3 2
++ Increment Unary num++ Evaluates to the value of num, increments num by 1.
-- Decrement Unary num-- Evaluates to the value of num, decrements num by 1.
+= Arithmetic compound-assignmentBinarynum += 5Adds 5 to the value of num and assigns the result to num. If num is 10, the new value of num will be 15.
-= Arithmetic compound assignment Binarynum -= 3Subtracts 3 from the value of num and assigns the result to num. If num is 10, the new value of num will be 7.
*= Arithmetic compound assignment Binarynum *= 15 Multiplies 15 to the value of num and assigns the result to num. If num is 10, the new value of num will be 150.
/= Arithmetic compound assignment Binarynum /= 5Divides the value of num by 5 and assigns the result to num. If num is 10, the new value of num will be 2.
%= Arithmetic compound assignment Binarynum %= 5Calculates the remainder of num divided by 5 and assigns the result to num. If num is 12, the new value of num will be 2.

Example of Using Java Operators

Demo

public class Main {
  public static void main(String[] args) {
    int num = 123;
    double realNum = 123.45F;
    double veryBigNum = 123.4 / 0.0;
    double garbage = 0.0 / 0.0;
    boolean test = true;

    System.out.println("num = " + num);
    System.out.println("realNum = " + realNum);
    System.out.println("veryBigNum = " + veryBigNum);
    System.out.println("garbage = " + garbage);
    System.out.println("test = " + test);
    System.out.println("12.5 + 100 = " + (12.5 + 100));
    System.out.println("12.5 - 100 = " + (12.5 - 100));
    System.out.println("12.5 * 100 = " + (12.5 * 100));
    System.out.println("12.5 / 100 = " + (12.5 / 100));
    System.out.println("12.5 % 100 = " + (12.5 % 100));
    System.out.println("\"abc\" + \"xyz\" = " + "\"" + ("abc" + "xyz") + "\"");

  }/*from  w ww .j a v  a  2  s  .  c  o  m*/
}

Result

Related Topics