Working with Arithmetic Operators - Java Language Basics

Java examples for Language Basics:Operator

Introduction

Java's Arithmetic Operators

OperatorDescription
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
++ Increment
-- Decrement

The following section of code can help clarify how these operators work for int types:

Demo Code

public class Main {
  public static void main(String[] args) {
    int a = 21, b = 6;
    int c = a + b;
    int d = a - b;
    int e = a * b;
    int f = a / b;
    int g = a % b;
    a++;// w w  w .  j  a  v a2  s.co m
    b--;

    System.out.println(a + " and " + b);

  }

}

Here's how the operators work for double values:

Demo Code

public class Main {
  public static void main(String[] args) {
    double x = 5.5, y = 2.0;
    double m = x + y;        // m is 7.5
    double n = x - y;        // n is 3.5
    double o = x * y;        // o is 11.0
    double p = x / y;        // p is 2.75
    double q = x % y;        // q is 1.5
    x++;                     // x is now 6.5
    y--;                     // y is now 1.0


    System.out.println(x + " and " + y);

  }// www  .j av a 2s  . c  om

}

Related Tutorials