posted 10 months ago

**Question :**Long has more memory than int . During converting how is that possible, suppose long max value is 10 digits and int has 8 digits i want to convert long into int and i put value = 9876321345 (10 digits i.e Max Value) will it convert it into int . While int contain only 8 digits storage >> How this type of conversion happen in java ?

I am Noob Looking for Experts for their suggestion and Ideas

posted 10 months ago

Actually their are some rules for the possible conversion in Java® Language specification.

For the question-suppose you have an long value as:

long longValue = 9_223_372_036_854_775_807L → which is (2^63)-1

in bits it is

01111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111

if you would try this:

int intValue = (int) longValue

this is a type of narrowing conversion(long to int) here you would of course going to loose some bits information.here you would loose the most significant 32 bits because int can only represent 32 bits so the intValue here is:

intValue: 11111111 11111111 11111111 11111111

this is a binary form of intValue.you can see it is a negative number as in java negative numbers are represented by 2's complement notation.so the bits above is a 2's complement representation which is (-1) in decimal.for a proof run this program:

Hope it helps!

Kind Regards,

Praveen.

For the question-suppose you have an long value as:

long longValue = 9_223_372_036_854_775_807L → which is (2^63)-1

in bits it is

01111111 11111111 11111111 11111111 11111111 11111111 11111111 11111111

if you would try this:

int intValue = (int) longValue

this is a type of narrowing conversion(long to int) here you would of course going to loose some bits information.here you would loose the most significant 32 bits because int can only represent 32 bits so the intValue here is:

intValue: 11111111 11111111 11111111 11111111

**→**[ loosed bits: 01111111 11111111 11111111 11111111 ]this is a binary form of intValue.you can see it is a negative number as in java negative numbers are represented by 2's complement notation.so the bits above is a 2's complement representation which is (-1) in decimal.for a proof run this program:

Hope it helps!

Kind Regards,

Praveen.

Try to enjoy your work while doing it,it will Automatically convert in Hard Work...