Primitive Data Types
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
Size | 8-bits |
Default Value | 0 |
Range | -128 to +127 |
Format | Signed two’s complement. |
short
Size | 16-bits |
Default Value | 0 |
Range | -32768 to +32767 |
Format | Signed two’s complement. |
int
Size | 32-bits |
Default Value | 0 |
Range | |
Format | Signed 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
Size | 64-bits |
Default Value | 0L |
Range | to |
Format | Signed two’s complement. |
float
Size | 32-bits |
Default Value | 0.0f |
Range | Variable |
Format | Single-precision 32-bit IEEE 754 floating point. |
double
Size | 64-bits |
Default Value | 0.0d |
Range | Variable |
Format | Double-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
Size | Variable (not specified by Java standard) |
Default Value | false |
Range | true or false |
Format | Not 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
Size | 16-bits |
Default Value | ’\u0000’ |
Range | ’\u0000’ to ‘\uffff’ |
Format | A 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 typemyByte = 240;
// This next one is o.k.// myByte = -16, or 0b11110000, which is the same bit-pattern// as the int 240myByte = (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 assignmentbyte 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 = -16int myInt = myByte & 0xFF;
myInt = (int)myByte;// myInt is now = - 16