3.17 Numeric data types
float is the most commonly-used floating-point type.
false Today, double is. Decades ago, float was, but then larger computer memories allowed programmers to use a floating-point type that was "double" the size of float, hence the name.
The number of days in a human's lifetime. int numDaysLife;
true The number might be as big as about 100 yrs * 365 days/year or 36,500. int can hold up to about 2 billion, so is large enough.
common error
A common error made by a program's user is to enter the wrong type, such as entering a string when the input statement was myInt = scnr.nextInt(); where myInt is an int, which can cause strange program behavior.
Floating-point numbers
Floating-point numbers are sometimes used when an integer exceeds the range of the largest integer type. On some processors, especially low-cost processors intended for "embedded" computing, like systems in an automobile or medical device, floating-point calculations may run slower than integer calculations, such as 100 times slower. Floating-point types are typically only used when really necessary. On more powerful processors like those in desktops, servers, smartphones, etc., special floating-point hardware nearly or entirely eliminates the speed difference.
The number of days of school per year: int numDaysSchoolYear;
true Although the max is 366, int is typically used rather than short.
Integer Types
Indicate whether each is a good variable declaration for the stated purpose, assuming int is usually used for integers, and long is only used when absolutely necessary.
The number of human heartbeats in one year, assuming 100 beats/minute. long numHeartBeats;
false 100 beats/min * 60 min/hr * 24 hr/day * 365 days/yr yields 52,560,000 beats/yr. 52 million is much less than an int's 2 billion max. A long is not necessary.
int and double types are limited to about 16 digits.
false A double's mantissa is limited to 16 digits (due to the number of bits that represent the mantissa), but an int's range is about +/- 2 billion which means 10 digits.
The number of cells in the average human body. int numCells;
false The human body contains approximately 37.2 trillion cells, exceeding the roughly 2 billion limit of an int. A long is needed.
Numeric data types
int and double are the most common numeric data types. However, several other numeric types exist. The following table summarizes available integer numeric data types.
overflow
occurs when the value being assigned to a variable is greater than the maximum value the variable can store. Overflow with floating-point results in infinity. Overflow with integer is discussed elsewhere.