Primitive number types in Java are categorized into two groups:
Integer types stores whole numbers, both positive and negative (e.g., 123 or -456), without decimals. These types include byte, short, int, and long, and the choice of type depends on the range of the numeric value.
Floating-point types represent numbers with fractional parts, encompassing one or more decimals, comprising two variations: float and double.
While Java offers various numeric types, the primary ones used for numbers are ‘int’ for whole numbers and ‘double’ for floating-point numbers. However, we’ll delve into each type as you read further. |
The byte data type has a range from -128 to 127, allowing it to store whole numbers within this range. It can serve as an alternative to int or other integer types, particularly when memory conservation is a concern and you’re confident the value will fall within -128 and 127.
|
The short data type encompasses whole numbers within the range of -32768 to 32767.
|
The int data type accommodates whole numbers ranging from -2147483648 to 2147483647. Typically, and as emphasized in our tutorial, the int data type is the preferred choice for creating variables with numeric values.
|
The long data type encompasses whole numbers spanning from -9223372036854775808 to 9223372036854775807. It is employed when the range of int is insufficient to accommodate the value. It’s noteworthy to append the value with an “L”.
Example
|
Whenever a number with a decimal point, such as 9.99 or 3.14515, is required, it’s advisable to utilize a floating-point type.
Both the float and double data types are suitable for storing fractional numbers. Remember to append the value with “f” for floats and “d” for doubles.
|
|
Use float or double?Consider precision, which refers to the number of digits a value can have after the decimal point. Floats offer a precision of merely six or seven decimal digits, whereas doubles boast a precision of approximately 15 digits. Hence, for most calculations, it’s advisable to opt for double due to its higher precision, ensuring safer and more accurate results. |
A floating-point number may also be expressed in scientific notation, denoted by an “e” to signify the power of 10.
|