Arithmetic Operators in Java


Arithmetic operators are the most widely used operators of the Java language simply because they're used to compute numbers.
There are four different arithmetic operators, namely:

+ (addition)
- (subtraction)
* (multiplication)
/ (division)
% (modulo)
- (unary minus)

Arithmetic operators can be used on any primitive data type except for boolean.

Here are some examples of how to use them:


//addition
int i = 5, j = 6;
System.out.println(i + j);


//subtraction
float i1 = 5;
int j1 = 6;
System.out.println(i1 + j1);


//multiplication
int i2 = 5, j2 = 6;
System.out.println(i2 * j2);


//division
double i3 = 5;
int j3 = 6;
System.out.println(i3 j3);

//modulo
int i4 = 15, j4 = 4;
System.out.println(i4 % j4);

//unary minus
int i5 = 5;
System.out.println(-i5);



Modulo returns the remainder when the first operand is divided by the second operand an integral number of times.
The unary minus simply converts a positive number to a negative (or a negative number to positive, like -(-5)).

It's important to remember that if one of the operands is a floating-point number, floating-point arithmetic will be used.
If not then integer arithmetic will be used, so the output of the above code will look like this:


11
11.0
30
0.8333333333333334
3
-5

Previous     Next

Tutorial Home


Do you know your Java?
Take a Ten-Question-Java-Quiz!

Bookmark and Share




Need help with your Java code? It's secure and confidential.
This is how it works:
Send a detailed description of what you need help with, the more details the better. Also provide a deadline for when it has to be finished. More time means better chance of putting your request into the schedule.

If the request is serious you will shortly receive an email with the price, to which you have to respond if you accept.

Once you have accepted, the work will begin on developing your code by an experienced Java developer. When the code is finished a link to a secure payment will be sent to you.

The source code is then sent to you once the payment is completed.

IMPORTANT! The request needs to be very detailed, else it may be ignored.


Write your detailed request here:

E-mail address: