2

I'm writing some code where I have to cast a long to an int. The input comes in as a string and the actual number is too large to immediately parse as an int. So I tried parsing as a long and then casting to an int, which worked and confused me because I though it wouldn't.

public void setNum(String Num) {
   if (Num != null){
       //THIS MAKES NO SENSE **to me** :(
        this.Num = (int) Long.parseLong(Num); 
   } else {
        this.Num = -1;
   }
}

I've read up on a couple other topics that I've found on here, notably this one and while it goes over how to safely convert them, it doesn't explain how the process works and I'm curious as to how it does. I know that in cases where the long is > Integer.MAX_VALUE will result in data being changed when it's casted, I'm still just confused as to how the casting actually works.

Scrambo
  • 579
  • 5
  • 17

1 Answers1

2

If Long.parseLong(Num) returns a value higher than Integer.MAX_VALUE or lower than Integer.MIN_VALUE, casting it to int will result in an incorrect value.

For positive longs, casting them to int simply means assigning the 32 lowest bits to the integer variable. I'm not sure if it's the same for negative longs (I'll have to check).

Eran
  • 387,369
  • 54
  • 702
  • 768