Java Math Operators

Java provides a rich set of operators to use in manipulating variables. A value used on either side of an operator is called an operand.
For example, in the expression below, the numbers 5 and 8 are operands of the plus operator:

 int a = 5 + 8;

Java arithmetic operators:

1.   + addition
2.   – subtraction
3.   * multiplication
4.    / division
5.   % modulo

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebraic equations.

Addition:

The + operator adds together two values, such as two constants, a constant and a variable, or a variable and a variable. Here are a few examples of addition:

int a = 40 + 10; 
int b = a + 34; 
int c = a + b;

Subtraction:

The – operator subtracts one value from another.

int a = 100 - 15;
int b = a - 5;
int c = a - b;

Multiplication:

The * operator multiplies two values.
int a = 100 * 6;
int b = a * 3;
int c = b * c;

Division:

The / operator divides one value by another.

int x = 500 / 5;
int y = x / 4;
int z = x/ y;

In the example above, the result of the division equation will be a whole number, as int is used as the data type. You can use double to retrieve a value with a decimal point.

Modulo:

The modulo (or remainder) math operation performs an integer division of one value by another, and returns the remainder of that division.
The operator for the modulo operation is the percentage (%) character.
Example:

int value = 36;
int result = value % 5; // result is 1

Dividing 36 by 5 returns a quotient of 7, with a remainder of 1. Thus, the value of 1 is assigned to the result variable.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s