Skip to content

Primitive Data Types

Published On:
Jun 8, 2016
Last Updated:
Jun 8, 2016

Java has 8 primitive data types. It does not support unsigned primitive types (all primitive numerical types are signed).

You cannot use the new keyword with primitive data types as they are not considered objects.

byte

Size8-bits
Default Value0
Range-128 to +127
FormatSigned two’s complement.

short

Size16-bits
Default Value0
Range-32768 to +32767
FormatSigned two’s complement.

int

Size32-bits
Default Value0
Range231to23112^{31} to 2^{31} - 1
FormatSigned two’s complement.

int literals can be created by just writing integers directly in the code. An integer is always of type int unless it is prefixed with an L or l, in which case it is of type long.

int i = 1234; // The 1234 is an integer literal

long

Size64-bits
Default Value0L
Range2632^{63} to 26312^{63} - 1
FormatSigned two’s complement.

float

Size32-bits
Default Value0.0f
RangeVariable
FormatSingle-precision 32-bit IEEE 754 floating point.

double

Size64-bits
Default Value0.0d
RangeVariable
FormatDouble-precision 64-bit IEEE 754 floating point.

The double type should be your default go-to for any general-purpose decimal number. If you are using many of them and space/performance is an issue, consider using the smaller, lower accuracy float type instead.

boolean

SizeVariable (not specified by Java standard)
Default Valuefalse
Rangetrue or false
FormatNot specified by Java standard.

Even though a boolean can only be used to represent one bit of information, the amount of memory it uses isn’t specified by the Java standard.

char

Size16-bits
Default Value’\u0000’
Range’\u0000’ to ‘\uffff’
FormatA single 16-bit Unicode character.

Converting Between byte And int

Notice that the only 8-bit number representation Java has is for a signed two complement. This means that you can only store the numbers -128 to +127 in a byte.

byte myByte;
// Compiler will throw error, 240 is outside the maximum range
// of the byte type
myByte = 240;
// This next one is o.k.
// myByte = -16, or 0b11110000, which is the same bit-pattern
// as the int 240
myByte = (byte)(240);

Note here that when converting from an int to a byte, the bit pattern will not be changed (0b11110000 is still 0b11110000), but the decimal representation will (e.g. 240 is now -16).

People with a C/C++ background would be used to datatype uint8_t, which is an unsigned 8-bit number, and allows you to store numbers between 0 to 255.

Above we have shown you how to convert from a int to a byte. Converting back is slightly different…

// myByte will equal -16 after this assignment
byte myByte = (byte)240;
// Woah, what???
// This is needed to tell Java to get the bits from myByte and
// plonk them into myInt. myInt should = 240 after this assignment.
// If you instead let Java do a "conversion" from
// byte to int, you will get myInt = -16
int myInt = myByte & 0xFF;
myInt = (int)myByte;
// myInt is now = - 16