Search code examples
javatypescastingintlong-integer

Why is casting to int giving me 8 instead of 0?


Sorry if this is simple. This has been confusing me for some time now. In the following code:

public class Main {
    public static void main(String[] args) {
        long a = 10000000000L;
        System.out.println(a % 10);
    }
}

I get an output of 0 which is what I expected. But when I cast to int like this,

public class Main {
        public static void main(String[] args) {
            long a = 10000000000L;
            System.out.println((int)a % 10);
        }
}

I get 8 as output instead of 0. I do not understand what is happening. Why is 0 turning into 8 after casting?


Solution

  • That happens because first is casting the value of a to int and then doing the module.

    What you want to do is:

    public class Main {
            public static void main(String[] args) {
                long a = 10000000000L;
                System.out.println((int)(a % 10));
            }
    }