In Java, data types are divided into two categories: primitive data types and reference data types. Understanding these is crucial for effective programming in Java.
Primitive data types are predefined by the language and named by a reserved keyword. They represent simple values and include:
Data Type | Size | Range | Use |
---|---|---|---|
byte | 8 bits | -128 to 127 | Saving memory in large arrays |
short | 16 bits | -32,768 to 32,767 | Saving memory in large arrays |
int | 32 bits | -2^31 to 2^31-1 | Default choice for integer values |
long | 64 bits | -2^63 to 2^63-1 | Wider range than int |
float | 32 bits | ±3.40282347E+38F (6-7 digits) | Single-precision floating point calculations |
double | 64 bits | ±1.79769313486231570E+308 (15 digits) | Double-precision floating point calculations |
boolean | 1 bit* | true or false | Flags for true/false conditions |
char | 16 bits | ‘\u0000’ to ‘\uffff’ (0 to 65,535) | Storing characters |
*Note: The exact size of a boolean is not precisely defined but is typically a single bit.
Reference data types are created using defined constructors of the classes. They are used to store references (addresses) of objects and can be used to call methods to perform certain operations. They include:
Data Type | Description | Use |
---|---|---|
Class | Blueprint for objects with data fields (attributes) and methods | Creating objects, defining methods and variables |
Interface | Abstract type specifying behavior that classes must implement | Achieving abstraction and multiple inheritance |
Array | Container holding a fixed number of values of a single type | Storing multiple values in a single variable |
String | Special class for sequences of characters (immutable) | Handling and manipulating textual data |