Data Types in Java
Data types in Java are divided into two main categories: primitive data types and reference (or non-primitive) data types. Here’s a detailed explanation of each:
Primitive Data Types in Java
Primitive data types are the most basic data types available within the Java language. There are eight primitive data types:
byte:
- Size: 8-bit
- Range: -128 to 127
- Example:
byte b = 100;
short:
- Size: 16-bit
- Range: -32,768 to 32,767
- Example:
short s = 10000;
int:
- Size: 32-bit
- Range: -2^31 to 2^31-1
- Example:
int i = 100000;
long:
- Size: 64-bit
- Range: -2^63 to 2^63-1
- Example:
long l = 100000L;
float:
- Size: 32-bit (single-precision floating point)
- Range: Approximately ±3.40282347E+38F (6-7 significant decimal digits)
- Example:
float f = 234.5f;
double:
- Size: 64-bit (double-precision floating point)
- Range: Approximately ±1.79769313486231570E+308 (15 significant decimal digits)
- Example:
double d = 123.4;
boolean:
- Size: Not precisely defined (commonly represented as 1 bit, but not specified)
- Values:
true
orfalse
- Example:
boolean b = true;
char:
- Size: 16-bit (single 16-bit Unicode character)
- Range: ‘\u0000’ (or 0) to ‘\uffff’ (or 65,535 inclusive)
- Example:
char c = 'A';
Reference Data Types in Java
Reference data types are based on classes. They include objects, arrays, and other class types. They reference memory locations where data is stored. Key reference data types include:
Objects:
- Objects are instances of classes.
- Example:
String str = "Hello, World!";
Arrays:
- Arrays are containers that hold multiple values of the same type.
- Example:
int[] arr = {1, 2, 3, 4, 5};
Classes:
- A class defines a new data type, representing a blueprint for objects.
- Example:
class MyClass { int x; }
Interfaces:
- Interfaces are abstract types that allow the specification of methods that classes must implement.
- Example:
interface MyInterface { void myMethod(); }
Differences between Primitive and Reference Data Types
Memory Allocation:
- Primitive types are stored directly in the memory allocated for the variable.
- Reference types store a reference (address) to the memory location where the data is stored.
Default Values:
- Primitive types have default values (e.g., 0 for int, false for boolean).
- Reference types default to
null
if they are not initialized.
Operations:
- Primitive types support arithmetic and logical operations directly.
- Reference types support operations defined by methods within the class.
Performance:
- Primitive types are generally faster because they are simple data types.
- Reference types are slower due to the overhead of referencing objects.
Understanding these data types is fundamental to programming in Java, as they form the basis for variable declaration, manipulation, and the overall structure of the code.