Java Numbers

Java Number Types

Java has a variety of numeric types which can be split into two main categories: integers and floating point numbers.


Integer Types

Integers store whole numbers, whether they’re positive or negative, without any decimals. Depending on the value you need, you can use byte, short, int, or long.



Byte

The byte data type can store whole numbers from -128 to 127. It’s useful for saving memory in situations where the range of the number fits within -128 to 127.

Example:

byte smallNum = 100;
System.out.println(smallNum);




Short

The short data type can store whole numbers from -32,768 to 32,767.

Example:

short mediumNum = 5000;
System.out.println(mediumNum);




Int

The int data type can store whole numbers from -2,147,483,648 to 2,147,483,647. It’s the most commonly used type for numeric values.

Example:

int largeNum = 100000;
System.out.println(largeNum);




Long

The long data type can store whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this when int isn’t large enough. Remember to end the value with an “L”.

Example:

long veryLargeNum = 15000000000L;
System.out.println(veryLargeNum);




Floating Point Types

Floating point types are used for numbers with a fractional part, containing one or more decimals. The two types are float and double.



Float

The float data type is for fractional numbers. It’s sufficient for storing 6 to 7 decimal digits. End the value with an “f”.

Example:

float decimalNum = 5.75f;
System.out.println(decimalNum);




Double

The double data type is for fractional numbers with more precision. It’s sufficient for storing 15 to 16 decimal digits. End the value with a “d”.

Example:

double preciseNum = 19.99d;
System.out.println(preciseNum);




Which to Use: Float or Double?

The precision of a floating point value indicates how many digits it can have after the decimal point. The float type has a precision of 6 to 7 decimal digits, while double has about 16 digits. For most calculations, it’s safer to use double.



Scientific Numbers

Floating point numbers can also be in scientific notation, using “e” to indicate the power of 10.

Example:

In this example, 35e3f means 35 × 10^3 and 12E4d means 12 × 10^4.

float scientificFloat = 35e3f;
double scientificDouble = 12E4d;
System.out.println(scientificFloat);
System.out.println(scientificDouble);
Scroll to Top