Groovy: What happens when you assign a BigInteger to an Integer

Have you ever tried assigning to large of a number to an Integer?

This question came in from a student in my Apache Groovy Development Course. It was actually quite interesting because it tripped me up at first before I understand what was going on behind the scenes. 

The Complete Apache Groovy Developer Course

The student was asking why when they created an integer but assigned to large of a number to it did the results end up like this.

Groovy Integer

Looking at the code example above can you see what is going on and why? Let’s take a minute and break this down. First, we are setting a very large number (BigInteger) to a data type integer. If you look at the Integer class there is a static MAX_VALUE that is set to “A constant holding the maximum value an int can have, 231-1.”

So we are trying to set a value that is outside of that max value range to an integer. When we print out the class though it’s still an integer

When we print out the value though it appears it is some random number.

You might expect this to just error out but that isn’t the case. What happens underneath the hood is that the number on the right is actually a BigInteger and when you try to assign it to an integer something happens. We end up calling the BigInteger’s class method int value which will convert that number to an integer. 


When you understand what is happening under the hood everything seems to make a lot more sense. 

Hi, I’m Dan Vega. I am a Software Engineer living just outside of one of my favorite places in the world, Cleveland, Ohio. I am a self-taught programmer who firmly believes that you can accomplish anything in this life if you put your mind to it, roll up your sleeves and are willing to put in the work.

I have been writing software for over 18+ years now and I use my knowledge, passion, and influence to help other developers achieve their goals. I teach online and currently, have over 30,000 students.

When I am not writing software, I have a number of things that really keep me busy. I love to read books, listen to podcasts and watch online courses. I have a real thirst for knowledge and it consumes me every single day of the week. I also love to run & lift heavy weights which keep me balanced throughout the week.

Please note: I reserve the right to delete comments that are offensive or off-topic.