Numbers
Java Numbers
Two categories comprise primitive number types:
Whole numbers, whether positive or negative (like 123 or -456), are stored as integer types without digits. The types byte, short, int, and long are acceptable. The numerical value determines the type to utilize.
Numbers having one or more decimals and a fractional portion are represented by floating point types. The two varieties are double and float.
Although Java has several different numeric types, the two most commonly used types are double (for floating point values) and int (for whole integers). Still, as you read on, we’ll go over each one in detail.
Integer Types
Byte
Whole numbers between -128 and 127 can be stored using the byte data type. When you are positive that the value will fall between -128 and 127, you can use this in place of int or other integer types to conserve memory:
Example
byte myNum = 100;
System.out.println(myNum);
Short
The full numbers from -32768 to -32767 can be stored in the short data type:
Example
short myNum = 5000;
System.out.println(myNum);
Int
The full numbers from -2147483648 to 2147483647 can be stored in an int data type. When we construct variables with a numeric value, the int data type is generally the preferred data type—this is also the case in our course.
Example
int myNum = 100000;
System.out.println(myNum);
Long
Whole numbers between -9223372036854775808 and 9223372036854775807 can be stored in the long data type. When int is too small to store the value, this is utilized. Keep in mind that a “L” should be used to finish the value:
Example
long myNum = 15000000000L;
System.out.println(myNum);
Floating Point Types
Whenever you need a number with a decimal, like 9.99 or 3.14515, you should use a floating point type.
Fractional numbers can be stored in the float and double data types. Keep in mind that a “f” should be used to terminate the value for floats and a “d” for doubles:
Float Example
float myNum = 5.75f;
System.out.println(myNum);
Double Example
double myNum = 19.99d;
System.out.println(myNum);
Use float or double?
The number of digits that can follow the decimal point in a floating point value is indicated by its precision. Whereas double variables have a precision of roughly 15 decimal places, float variables only have six or seven. For the majority of computations, it is therefore safer to utilize double.
Scientific Numbers
A scientific number with a “e” to represent the power of ten can also be a floating point number:
Example
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);