In this tutorial you will learn about Java primitive types and how to choose the right one.

Variables allocate space in computer memory. It is good to choose the right primitive type to save memory. For example: to store a lot of numbers in range from -128 to 127 into array declare your variables as `byte`

, not `int`

or `long`

int intVariable = 24; // uses 32 bits of memory long longVariable = 24L; // uses 64 bits of memory byte byteVariable = 24; // uses 8 bits of memory

In the example above we store the number 24 in 3 variables with different primitive types. Note the amount of memory allocation for the three types. `byte`

is 4 times smaller than `int`

and 8 times smaller than `long`

If you come from another programming language like C/C++, please note there are no unsigned data types in Java. All primitive types in Java are signed.

## byte

- Use
`byte`

to store lots of small numbers. - Uses 8 bit of memory
- Value range: minimum value of -128 and a maximum value of 127
- Default value is 0

## short

- Use
`short`

to store lots of small numbers, which are too big for a`byte`

- Uses 16 bit of memory
- Value range: minimum value of -32,768 and a maximum value of 32,767
- Default value is 0

## int

- Use to store or compute with integers. This is the most commonly used type
- Uses 32 bit of memory
- Value range: minimum value of -2,147,483,648 and a maximum value of 2,147,483,647
- Default value is 0

## long

- Use
`long`

to compute with integers too large for an`int`

- Uses 64 bit of memory
- Value range: minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807
- Default value is 0L

## float

- Use
`float`

to store or compute with rational numbers (numbers with decimal points or in scientific notation).`float`

has 6 decimal digits of accuracy - Uses 32 bit of memory
- Default value is 0.0f

## double

- Similar to
`float`

but with greater range and 14 decimal digits of accuracy - Uses 64 bit of memory
- Default value is 0.0d

## boolean

- There are only two possible values: true and false. Use
`boolean`

to flag true/false conditions - Uses 1 bit of memory
- Default value is false

## char

- Use
`char`

for Unicode character codes, including`'\\'`

,`'\n'`

,`'\r'`

,`'\t'`

,`'\''`

, and`'\uxxxx'`

- Uses 16 bit of memory
- Value range: minimum value of 0 and a maximum value of 65,535
- Default value is 0

In our next tutorial you will learn about Java variable types and how to use them.

## Leave a Reply

Be the First to Comment!