Java Numbers: Understanding Primitive Data Types

Dive into the world of primitive number types in Java, which are categorized into two main groups. This guide covers integer types, such as byte, short, int, and long, used for storing whole numbers without decimals, and floating point types, including float and double, which represent numbers with fractional parts. Enhance your understanding of numerical data management in Java with this comprehensive overview.



Java Numbers

Numbers

Primitive number types in Java are divided into two groups:

  • Integer types store whole numbers, positive or negative, without decimals. Valid types are byte, short, int, and long.
  • Floating point types represent numbers with a fractional part, containing one or more decimals. There are two types: float and double.

Even though Java supports many numeric types, the most commonly used are int (for whole numbers) and double (for floating point numbers).

Integer Types

Byte

The byte data type can store whole numbers from -128 to 127. It saves memory when you know the value will be within this range:

Example

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

Short

The short data type can store whole numbers from -32768 to 32767:

Example

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

Int

The int data type can store whole numbers from -2147483648 to 2147483647. It's generally preferred for numeric values:

Example

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

Long

The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807. Use it when int is not large enough. End the value with "L":

Example

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

Floating Point Types

Use a floating point type when you need a number with a decimal:

Float Example

Example

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

Double Example

The double data type can store more decimal values than float. End the value with "d":

Example

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

Scientific Numbers

A floating point number can be represented as a scientific number with an "e" to indicate the power of 10:

Example

float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);