TransWikia.com

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

Stack Overflow Asked on December 7, 2021

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?

2 Answers

As you are casting the long into int. And the value of long is beyond the range of int (-2,147,483,648 to 2,147,483,647). So when you try to cast it and store it in int data type than the JVM will simply round it of into the range of int data type. And the value which will be stored in int is 1410065408.

Now if you do the 1410065408 % 10 = 8.

You can try below program to verify the same.

public class Test {
    public static void main(String[] args) {
        long a = 10000000000L;
        int b = (int) a; 
        System.out.println(b);  // here it will print 1410065408 
        System.out.println(b % 10);  //so here it's 8
    }
}

Answered by Deepak Kumar on December 7, 2021

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

Answered by jeprubio on December 7, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP