| |
|
1.9 Primitive Data Types
Java implements a number of primitive data types found in most other typed programming languages as well.
| Keyword |
Description |
Size / Format |
Range |
| integers |
| byte |
Byte-length integer |
8-bit two's complement |
-128 to 127 |
| short |
Short integer |
16-bit two's complement |
-32,768 to 32,767 |
| int |
Integer |
32-bit two's complement |
-2,147,483,648 to 2,147,483,647 |
| long |
Long integer |
64-bit two's complement |
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
| real numbers |
| float |
Single-precision floating point |
32-bit IEEE 754 |
+/- 1.4E-45 to +/- 3.4028235E+38 |
| double |
Double-precision floating point |
64-bit IEEE 754 |
+/- 439E-324 to +/- 1.7976931348623157E+308 |
| other types |
| char |
A single character |
16-bit Unicode character |
\u0000 to \uFFFF |
| boolean |
A boolean value (true or false) |
true or false |
true, false |
Note that primitive data types all have
LOWERCASE initials. These primitive data types also have corresponding Object data types, e.g. int (Integer), boolean (Boolean), etc. Object classes in Java tend to have UPPERCASE initials.
Primitive data types are not Objects. They do not contain methods by which the values can be acted upon.
These data types can be used for initializations as follows:
-
byte b = 5;
-
short s = 10;
-
int i = 15;
-
long l = 20;
-
float f = 25.8;
-
double d = 30.12;
-
char c = 'J';
-
boolean b = true;
1.9.1 Operations on numerical data types
Operations on numerical data types include basic arithmetics:
+
, -
, *
, /
, e.g. a + b
, 7 * f
Furthermore, the modulus operator (
%
) can be used on integers, e.g. 10 % 4
Grouping of statements and operations is performed using parentheses:
(
, )
, e.g. (((4 + 5) * 10) - 90)
1.9.2 Operations on boolean
Booleans can be inverted using the exclamation mark (
!
), e.g. boolean myTrueValue = !false
This is mainly useful during loop executions, e.g.
while (!done)
1.9.3 Operations on char
Characters in Java are treated as integers. The character
y
, for example, has an ASCII value of 121
. It is valid to make the statement int i = 'y';
, in which case the integer value for i becomes 121.
It is similarly valid to add characters:
int i = 'w' + 'h' + 'y';
1.9.4 Casting
Data types can also be cast, for example when a
long value is to be interpreted as an int value, or an operation like int = int + double is desired. Casting data types can be achieved by parenthesizing the new type before the value:
- long to int:
(long)87
, or (long)mylongvariable
- in
int x = int i + double d: x = i + (int)d;
Shorter casting methods for numerical values include:
- long:
20L
- float:
25.8F
- double:
30.12D
, 30.12e5
|
|