r/learnjava • • Nov 30 '15

133 Java Interview Questions Answers From Last 5 Years

http://javarevisited.blogspot.com/2015/10/133-java-interview-questions-answers-from-last-5-years.html
60 Upvotes

5 comments sorted by

5

u/desrtfx Dec 01 '15

Datatypes -> Question #17:

17) What is the right data type to represent a price in Java?

BigDecimal if memory is not a concern and Performance is not critical, otherwise double with predefined precision.

BigDecimal is ok, but double? Never. If you want a smaller datatype use int or long and convert the price to the smallest monetary unit (i.e. Cents, Pennies, Dirham, etc.)

Even Oracle advises against using double for currency values:

float: ... This data type should never be used for precise values, such as currency.

double: ... As mentioned above, this data type should never be used for precise values, such as currency.

1

u/crooks5001 Dec 04 '15

Rookie question here: Why is this?

2

u/desrtfx Dec 05 '15

That is because computers calculate in binary numbers as opposed to our decimmal system.

While in the decimal system we use 1/10, 1/100, 1/1000 and so forth, the binary system uses 1/2, 1/4, 1/8, etc.

In both, the decimal and in the binary system numbers exist that can't be exactly represented, just think about 1/3 in the decimal system. It's worse in binary, though.

In addition to the above, computers store the numbers in a special format that is somewhat similar to scientific notation. They use 32 (or 64) bits to pack a mantissa (sort of the decimal part) and an exponent (sort of a multiplier) - for a 32 bits real it's 24 bits for the mantissa and 8 bits for the exponent.

You can find additional information in wikipedia - IEEE 754 floating point notation

1

u/crooks5001 Dec 05 '15

That's really interesting (no sarcasm.)

3

u/[deleted] Nov 30 '15

OP you are a god amongst the living.