A variable is a name for a location in memory used to hold a data value. Variable declarations instruct the compiler to reserve a portion of main memory space large enough to hold a particular type of value and indicates the name (user-defined identifier) by which we refer to that location.
A variable can store only one value of its declared type at any one time. A new value overwrites the old one. The Java language is strongly typed, meaning that we are not allowed to assign a value to a variable that is inconsistent with its declared type.
There are eight primitive data types in Java: four subsets of integers, two subsets of floating point (real) numbers, a character data type, and a Boolean data type. All other types are represented as objects, including the String data type.
Type Name | Size | Range of Values |
---|---|---|
byte | 1 byte | -128 to 127 |
short | 2 bytes | -32,768 to 32,767 |
int | 4 bytes | -2,147,483,648 to 2,147,483,647 |
long | 8 bytes | much more than we’ll need in this class |
Java assumes all integer literals are of type int, unless an L or l is appended to the end of the value to indicate it should be of type long. Only variables can be of type byte and short. (Note: a numeric literal (integer or floating point) is just a number that you write in your code).
Type Name | Size | Range of Values |
---|---|---|
float | 4 bytes | -3.4E+38 to 3.4E+38 with 7 significant digits |
double | 8 bytes | -1.7E+308 to 1.7+E308 with 15 significant digits |
Java assumes floating-point literals are of type double. If we need to treat a floating point literal as a float, we append F or f to the end of the value. For example, 2.178 will reserve 8 bytes because the compiler will store this literal as a double, while 2.178F or 2.178f will be stored in 4 bytes as a float.
There is only one character type, which is designated by the reserved word char and which uses 2 bytes of memory. Characters in Java are stored using the Unicode character set (16 bits). A char literal is any single character enclosed in single quotes.
There is only one boolean type, which is designated by the reserved word
boolean. A boolean variable can hold either the value true or the value false.
A boolean value cannot be converted to any other data type, nor can any other data
type be converted to a Boolean value.
The words true and false are reserved in Java as boolean literals and cannot be used
outside of this context.
Email Me |
Office Hours |
My Home Page |
Department Home |
MCC Home Page
© Copyright Emmi Schatz 2013