Variables in Java
Objectives
- Distinguish between primitive and reference variables
- Declare and use primitive variables
- Declare, create, and use reference variables
- Know sizes of primitive types
- Understand automatic promotion of primitive variables
- Understand type casting of primitive variables
Declaring a Variable
Assigning a Value to Variable
Initializing a Variable
Primitive or Reference
- Variables may be categorized by their type as either primitive
or reference.
- Primitive variables store only one value at a time and have no
methods.
- Reference variables refer to arrays or objects which may store
many values at once and may have methods.
- There are eight primitive types in Java.
- All other types are reference types.
| Primitive |
Reference |
| boolean | Everything else, such as: |
| char | Object |
| byte | String |
| short | StringBuilder |
| int | TreeSet |
| long | Integer |
| float | Long |
| double | Float |
Primitive Types
| Type |
Purpose |
Size (bytes) |
Examples |
| boolean |
Store true or false |
1 |
boolean b = true; |
| char |
Store a single unicode character |
2 |
char c = 'A'; |
| byte |
Store a number from this range
[-27, 27) =
[-128, 128) = [-128, 127] |
1 |
byte b = 12; |
| short |
[-215, 215) =
[-32768, 32768) =
[-32768, 32767] |
2 |
short s = -25000; |
| int |
[-231, 231) =
[-2147483648, 2147483648) |
4 |
int i = 4013; |
| long |
[-263, 263) =
[-9223372036854775808, 9223372036854775808) |
8 |
long n = 3; |
| float |
Store a floating point number (a number with digits after the
decimal separator) with approx. 7 decimal digits of precision |
4 |
float f = 4.15f; |
| double |
More precise than float, approx. 15 decimal digits of precision |
8 |
double d = 76.178032; |
Automatic Promotion of Primitive Variables
Type Casting Primitive Variables
- Larger variables cannot be "promoted" to smaller variable
types.
- Converting from larger to smaller is a "demotion" and may result
in lost data (possible loss of precision).
- The programmer must explicitly write a type cast to cause the
computer to convert from a larger variable to a smaller one.
- Examples:
double d = 6.7;
int i = d; // Wrong! Results in a compile error.
double d = 6.7;
int i = (int)d; // Correct type cast from double to int.
// After the type cast and assignment, i
// holds the value 6, d holds the value 6.7
Copyright © 2010, Maia L.L.C. All rights reserved.