Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you convert Integer.MIN_VALUE to a positive long?

I’m trying to convert this to a positive long but it is still printing as a negative. When I use other negative integers it works but not Integer.MIN_VALUE

 if(num == Integer.MIN_VALUE){
           long number = -num;
           System.out.println(number);
       }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

long num = -num; is executed as:

  1. take the int num, and negative it; it’s still an int. In other words, it remains Integer.MIN_VALUE – because that’s the one negative number amongst all 2^31 of em that doesn’t have a positive equivalent, as 0 ‘takes up space’ on the positive side of things.

  2. Then, take the number we now have (still Integer.MIN_VAUE, because -Integer.MIN_VALUE is still Integer.MIN_VALUE), and silently cast it to a long, because that’s a widening (safe) conversion, so java will just inject the cast for you.

The fix is to first cast to a long and then negative it:

either:

long number = num;
number = -number;

or in one go:

long number = -((long) num);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading