x = x * y / z is not equal to x *= y / z for integers – Code Example

Table of Contents Hide
  1. Reason
  2. Code Example
  3. Live Demo
    1. Related Posts

In this article we will understand why x=x*y/z is not equal to x*=y/z if variables are integers using java code example.

Reason

Let’s understand through mathematics –

Suppose, x = 5, y = 7, z = 3

1. If we use this equation – x = x * y / z then,

x = 5 * 7 / 3 = 35 / 3 = 11 (because we are dealing with integer variables).

2. If we use this format – x *= y / z then,

x *= 7 / 3
x *= 2
x = x * 2 = 5 * 2 = 10

So you can see that both results are different and this is due to neglection of remainder by division of integers. (x * y) / z != x * (y / z)

Code Example

public class MyClass {
    public static void main(String args[]) {
        int x = 5;
        int y = 7;
        int z = 3;
        
        x = x * y / z;
        System.out.println("x = x * y / z; x = " + x);
        
        x = 5;
        x *= y / z;
        System.out.println("x *= y / z; x = " + x);
    }
}

Output –

x = x * y / z; x = 11
x *= y / z; x = 10

Live Demo

Open Live Demo