-2

in my java code, I get the value of a as 814 and not 5814. why? what is wrong here? I'm using eclipse IDE. The following code gives:
814
5
14
4
4

public class Hello {

    int a = 5814;
    
    int m = (a/1000);
    int p = (a %= 1000);
    int q = (p %= 100);
    int r = (q %= 10);

    public Hello() {    
        
        System.out.println(a);
        System.out.println(m);
        System.out.println(p);
        System.out.println(q);
        System.out.println(r);
    }
        
    public static void main(String[] args) {
        
        new Hello();

    }
}
007
  • 5
  • 5

2 Answers2

1

In the line

int p = (a %= 1000);

the operator %= has a side effect on a: it assigns the value of the modulo operation to a (and also 'returns' it to get assigned to p); thus, overwriting its previous value. 5814 % 1000 = 814, which is what is correctly printed.

twwwt
  • 438
  • 1
  • 4
  • 16
  • ok. print statement just after ```int a = 5814; ``` will show 5814 then. understood. thanks! – 007 Aug 29 '22 at 16:26
0

because here(The variable a assigns itself the value mod 1000)

 int p = (a %= 1000);