๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Arithmetic Operators in Java  


Introduction

  • Arithmetic operators in Java are used to perform basic mathematical operations on numeric data types (e.g., int, float, double).
  • Arithmetic operators are explained as below :-
    • + (Addition operator): Adds two operands.
    • - (Subtraction operator): Subtracts the second operand from the first.
    • * (Multiplication operator): Multiplies two operands.
    • / (Division operator): Divides the first operand by the second.
    • % (Modulus operator): Returns the remainder when the first operand is divided by the second.
  • Program :
    public class ArithmeticOperators
    {
        public static void main(String[] args)
        {
            int a = 10, b = 5;
            double x = 10.5, y = 4.2;
    
            // Addition
            System.out.println("Addition (int): " + (a + b));  // Output: 15
            System.out.println("Addition (double): " + (x + y));  // Output: 14.7
    
            // Subtraction
            System.out.println("Subtraction (int): " + (a - b));  // Output: 5
            System.out.println("Subtraction (double): " + (x - y));  // Output: 6.3
    
            // Multiplication
            System.out.println("Multiplication (int): " + (a * b));  // Output: 50
            System.out.println("Multiplication (double): " + (x * y));  // Output: 44.1
    
            // Division
            System.out.println("Division (int): " + (a / b));  // Output: 2 (integer division)
            System.out.println("Division (double): " + (x / y));  // Output: 2.5
    
            // Modulus
            System.out.println("Modulus (int): " + (a % b));  // Output: 0
            System.out.println("Modulus (double): " + (x % y));  // Output: 2.1
        }
    }
    Output:
    Addition (int): 15
    Addition (double): 14.7
    Subtraction (int): 5
    Subtraction (double): 6.3
    Multiplication (int): 50
    Multiplication (double): 44.1
    Division (int): 2
    Division (double): 2.5
    Modulus (int): 0
    Modulus (double): 2.0999999999999996
Some Advance Important Points :-
  • Integer Division: When both operands are integers, the division operator (/) performs integer division, which truncates the decimal part. For example, 10 / 3 results in 3, not 3.333....
  • Floating-Point Division: When at least one operand is a floating-point number (float or double), division results in a floating-point value.
  • Modulus: The modulus operator returns the remainder of the division. For example, 10 % 3 results in 1 (because 10 divided by 3 gives a remainder of 1).