Java Arithmetic Operators
In this chapter you will learn:
- What are Java Arithmetic Operators
- Use Java Arithmetic Operators to do calculation
- Example - How to use basic arithmetic operators to do calculation
Description
Arithmetic operators are used in mathematical expressions.
All Arithmetic Operators
The following table lists the arithmetic operators:
Operator | Result |
---|---|
+ | Addition |
- | Subtraction (unary minus) |
* | Multiplication |
/ | Division |
% | Modulus |
++ | Increment |
+= | Addition assignment |
-= | Subtraction assignment |
*= | Multiplication assignment |
/= | Division assignment |
%= | Modulus assignment |
-- | Decrement |
The operands of the arithmetic operators must be of a numeric type.
You cannot use arithmetic operators on boolean
types, but you can use them on char
types.
Example
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.
The quick demo below shows how to do a simple calculation in Java with basic arithmetic operators.
public class Main {
/*w w w . j a v a 2s . co m*/
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);
int x = 42;
System.out.println("x mod 10 = " + x % 10);
double y = 42.25;
System.out.println("y mod 10 = " + y % 10);
}
}
When you run this program, you will see the following output:
The modulus operator, %
, returns the remainder of a division operation.
The modulus operator can be applied to floating-point types as well as integer types.
Next chapter...
What you will learn in the next chapter:
- What are Arithmetic Compound Assignment Operators
- Syntax for Arithmetic Compound Assignment Operators
- Example - Arithmetic Compound Assignment Operators