The Basic Arithmetic Operators

The basic arithmetic operations are addition, subtraction, multiplication, and division. They behave as you would expect. The minus operator also has a unary form which negates its single operand.

 
public class Main {

  public static void main(String args[]) {

    System.out.println("Integer Arithmetic");
    int a = 1 + 1;
    int b = a * 3;
    int c = b / 4;
    int d = c - a;
    int e = -d;
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    System.out.println("c = " + c);
    System.out.println("d = " + d);
    System.out.println("e = " + e);

  }
}

When you run this program, you will see the following output:


Integer Arithmetic
a = 2
b = 6
c = 1
d = -1
e = 1

When the division operator is applied to an integer type, there will be no fractional component attached to the result.

 
public class Main {
  public static void main(String args[]) {

    // arithmetic using doubles
    System.out.println("Floating Point Arithmetic");
    double da = 1 + 1;
    double db = da * 3;

    System.out.println("da = " + da);
    System.out.println("db = " + db);

  }
}

When you run this program, you will see the following output:


Floating Point Arithmetic
da = 2.0
db = 6.0
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.