There are just 8 primitive data types. We have already met int
but there are 3 other types for whole numbers. They differ in the range of values they can hold. All are signed (unlike C/C++ there are no unsigned versions). They all use their top bit to indicate sign:
byte
a single byte, values -128 to +127short
2 bytes, values -32,768 to +32,767 (ie, -215 to +215 - 1)int
4 bytes, values -231 to +231 - 1long
8 bytes, -263 to +263 - 1To force a number to be treated as long
rather than the default int
append the letter L to it. Eg,
long msPerYear = 365L * 24L * 60L * 60L * 1000L; // milliseconds per year
In this example failure to use the letter L results in the expression being evaluated as an int
and the value overflows the maximum possible value for an int
.
There are 2 data types for floating point (ie, non-integral) numbers, eg -1.234E-5, where E means "10 to the power of" - the same as in most programming languages:
float
4 bytes (7 decimal digit accuracy)double
8 bytes (16 decimal digit accuracy)The default treatment for a floating-point number is double
. To force a number to be treated as a float
you must put the letter F after it. Eg,
float pi = 3.141596F;
There are 2 other primitive types:
boolean
has just 2 possible values, defined by the keywords false
and true
. These cannot be equated to any numerical values.char
2 bytes, representing a single (Unicode) character, eg 'A'
or '\u0041'
(explained soon).That is all of the so-called primitive data types. Other data types are classes, interfaces and enums, of which there can be as many as you care to define. We will come to those later.