1. Java Types
In Java, data types are divided into two main categories: Primitive Types and Reference (Object) Types. Understanding these types is crucial for effective programming in Java.
1. Primitive Types
Primitive types are the basic data types provided by Java. They are not objects and hold their values directly in memory. Java has eight primitive data types:
| Type | Size (in bytes) | Default Value | Description |
|---|---|---|---|
| byte | 1 | 0 | 8-bit signed integer |
| short | 2 | 0 | 16-bit signed integer |
| int | 4 | 0 | 32-bit signed integer |
| long | 8 | 0L | 64-bit signed integer |
| float | 4 | 0.0f | Single-precision 32-bit floating-point |
| double | 8 | 0.0 | Double-precision 64-bit floating-point |
| char | 2 | '\u0000' | Single 16-bit Unicode character |
| boolean | 1 (not precisely defined) | false | Represents true or false values |
public class PrimitiveExample {
public static void main(String[] args) {
int number = 10; // Integer
char letter = 'A'; // Character
boolean isActive = true; // Boolean
}
}
2. Object (Reference) Types
Reference types, also known as object types, refer to objects and hold a reference to the memory location where the object is stored. They can be created from classes, interfaces, and arrays. Key characteristics include:
- Dynamic Size: The size of an object is determined at runtime.
- Null Reference: A reference type can be assigned a
nullvalue, indicating that it does not point to any object.
Common Object Types:
| Type | Description |
|---|---|
| Classes | User-defined data types that encapsulate data and behavior. |
| Interfaces | Abstract types that define a contract for classes to implement. |
| Arrays | A collection of elements of the same type, stored in contiguous memory locations. |
public class ObjectExample {
public static void main(String[] args) {
String text = "Hello, World!"; // String object
Integer number = new Integer(10); // Integer object
int[] numbers = {1, 2, 3, 4, 5}; // Array of integers
}
}
3. Summary of Java Types
| Type Category | Description | Examples |
|---|---|---|
| Primitive Types | Basic data types holding their values directly. | int, char, boolean |
| Reference Types | Hold references to objects in memory. | String, Array, Custom Class |
4. Key Differences Between Primitive and Reference Types
| Feature | Primitive Types | Reference Types |
|---|---|---|
| Storage | Directly stores values | Stores references to objects |
| Size | Fixed size (defined by type) | Dynamic size (depends on object) |
| Default Value | Has a default value | Default is null |
| Null Value | Cannot be null | Can be null |