sam
sam

Reputation: 63

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?

Upvotes: 2

Views: 326

Answers (2)

Deepak Kumar
Deepak Kumar

Reputation: 1304

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

Upvotes: 3

jeprubio
jeprubio

Reputation: 18032

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

Upvotes: 3

Related Questions