| |
Basic Data Types in Java | page 4 of 11 |
Java provides eight primitive data types: byte , short , int , long , float , double , char and boolean . The data types byte , short , int , and long are for integers, and the data types float and double are for real numbers.
Integer type - any positive or negative number without a decimal point.
Examples: 7 -2 0 2025
Floating Point type - any signed or unsigned number with a decimal point.
- Examples:
7.5 -66.72 0.125 5.
- A floating point value cannot contain a comma or $ symbol.
- A floating point value must have a decimal point.
- Invalid examples:
1,234.56 $66.95 125 7,895
- Floating point values can be written using scientific notation:
1625. = 1.625e3 .000125 = 1.25e-4
The following table summarizes the bytes allocated and the resulting size.
| Size | Minimum Value | Maximum Value | | | | | byte | 1 byte | -128 | 127 | short | 2 bytes | -32768 | 32767 | int | 4 bytes | -2147483648 | 2147483647 | long | 8 bytes | -9223372036854775808 | 9223372036854775807 | float | 4 bytes | -3.40282347E+38 | 3.40282347E+38 | double | 8 bytes | -1.79769313486231570E+308 | 1.79769313486231570E+308 |
Character type - letters, digits 0...9, and punctuation symbols.
- Examples:
'A' , 'a' , '8' , '*'
- Note that a character type must be enclosed within single quotes.
- Java character types are stored using 2 bytes, usually according to the ASCII code. ASCII stands for American Standard Code for Information Interchange.
- The character value 'A' is actually stored as the integer value 65. Because a capital 'A' and the integer 65 are physically stored in the same fashion, this will allow us to easily convert from character to integer types, and vice versa.
- Using the single quote as a delimiter leads to the question about how to assign the single quote (
' ) character to a variable. Java provides escape sequences for unusual keystrokes on the keyboard. Here is a partial list:
| Character | Java Escape Sequence | | | | | Newline | ' \n' | | Horizontal tab | ' \t' | | Backslash | ' \\' | | Single quote | ' \' | | Double quote | ' \"' | | Null character | ' \0' |
Data types are provided by high level languages to minimize memory usage and processing time. Integers and characters require less memory and are easier to process. Floating-point values require more memory and time to process.
The final primitive data type is the type boolean . It is used to represent a single true /false value. A boolean value can have only one of two values:
true false
In a Java program, the words true and false always mean these boolean values.
|