List of Arithmetic Operators in Java - Java Language Basics

Java examples for Language Basics:Operator

Introduction

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-assignment Binarynum += 5Adds 5 to the value of num and assigns the result to num.
-= Arithmetic compound assignment Binarynum -= 3Subtracts 3 from the value of num and assigns the result to num.
*= Arithmetic compound assignment Binarynum *= 15 Multiplies 15 to the value of num and assigns the result to num.
/= Arithmetic compound assignment Binarynum /= 5Divides the value of num by 5 and assigns the result to num.
%= Arithmetic compound assignment Binarynum %= 5Calculates the remainder of num divided by 5 and assigns the result to num.

Demo Code

public class Main {
  public static void main(String[] args) {
    int i = 110;//  w  w  w  .j a v  a 2s  .com
    float f = 120.2F;
    byte b = 5;
    String str = "Hello";
    boolean b1 = true;

    i += 10; // Assigns 120 to i

    i -= 15; // Assigns 95 to i. Assuming i was 110
    i *= 2; // Assigns 220 to i. Assuming i was 110
    i /= 2; // Assigns 55 to i. Assuming i was 110
    i /= 0; // A runtime error . Division by zero error
    f /= 0.0; // Assigns Float.POSITIVE_INFINITY to f
    i %= 3; // Assigns 2 to i. Assuming i is 110

    str += " How are you?"; // Assigns "Hello How are you?" to str
    str += f; // Assigns "Hello120.2" to str. Assuming str was "Hello"
    b += f; // Assigns 125 to b. Assuming b was 5, f was 120.2
    str += b1; // Assigns "Hellotrue" to str. Assuming str was "Hello"
  }
}

Related Tutorials