Arithmetic operators are used to do arithmetic operations on data and variables. Java supports below arithmetic operators
Addition is denoted by + sign. It gives the sum of two numbers
class Addition { public static void main(String[] args) { System.out.println(2 + 5); System.out.println(1 + 1.5); } } |
Output:
7
2.5
Subtraction is denoted by - sign. It gives the difference between the two numbers
class Subtraction { public static void main(String[] args) { System.out.println(5 - 2); } } |
Output:
3
Multiplication is denoted by * sign. It gives the product of two numbers
class Multiplication { public static void main(String[] args) { System.out.println(5 * 2); System.out.println(5 * 0.5); } } |
Output:
10
2.5
Division is denoted by / sign. It returns the quotient as a result. In contrast to Python which returns a float, Java returns an integer. During division, Python internally converts the integer values to float data type. The conversion of one data type to another data type is called Type Conversion. We will learn more about Type Conversions later in the course
class Division { public static void main(String[] args) { System.out.println(5 / 2); System.out.println(4 / 2); } } |
Output:
2
2
Modulo is denoted by % sign. It returns the modulus (remainder) as a result
class Modulus { public static void main(String[] args) { System.out.println(5 % 2); System.out.println(4 % 2); } } |