Home > Blockchain >  Java code int value not showing correctly
Java code int value not showing correctly

Time:08-30

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();

    }
}

CodePudding user response:

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.

CodePudding user response:

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

 int p = (a %= 1000);
  • Related