1. What Is a Data Type?
A data type is a set of rules by which a programming language classifies and constrains data, defining the range of values, the storage representation, the permitted operations, and the type compatibility relationships.
In essence, all information processed by a program must be expressed through some data type.
For example:
int age = 25;
double price = 99.99;
boolean enabled = true;
String name = "Alice";
These variables represent an integer, a floating-point number, a boolean, and a string, respectively.
Different data types have different characteristics:
- Integers support arithmetic operations.
- Floating-point numbers support approximate real-number arithmetic.
- Booleans represent logical states.
- Strings represent sequences of text.
- Arrays are used to organize multiple elements.
- Objects are used to combine multiple properties and behaviors.
Data types affect not only how a program uses data, but also how the compiler generates code, how memory is allocated at runtime, and how data is passed between functions.
1. The Main Roles of Data Types
| Role | Description |
|---|---|
| Data representation | Defines how data is represented in memory or another storage medium |
| Value constraints | Restricts the values or states that data can represent |
| Operation constraints | Defines the operations that data is allowed to perform |
| Type checking | Checks whether variables, expressions, and functions conform to the type rules |
| Memory management | Affects the storage layout, size, and lifetime management of data |
| Abstract modeling | Uses structured types to express complex business entities |
2. Perspectives on Classifying Data Types
Primitive data types and composite data types are a common way of classifying types, but not every programming language adopts exactly the same classification system.
From different perspectives, data types can be divided into:
| Classification Dimension | Types |
|---|---|
| Structural complexity | Primitive data types, composite data types |
| Type system | Built-in types, user-defined types |
| Data organization | Scalar types, aggregate types |
| Data access | Value types, reference types (some languages use this classification) |
| Type behavior | Mutable types, immutable types |
| Type checking | Static types, dynamic types |
Note that these classification dimensions are not mutually exclusive.
For example, a struct can be both a user-defined type and a composite type; in Rust, it has value semantics, yet internally it can still contain references or smart pointers.
2. Primitive Data Types
Primitive data types are usually the basic data types provided by a programming language, used to represent single, relatively simple data values.
They form the foundation of more complex data structures.
Common primitive data types include:
- Integer types
- Floating-point types
- Boolean types
- Character types
- Byte types
- Null / Unit types in some languages
1. Integer Types
Integer types are used to represent numeric values with no fractional part.
For example:
int age = 25;
long population = 8000000000L;
short temperature = 20;
byte level = 10;
Common integer types:
| Type | Common Bit Width | Typical Use |
|---|---|---|
| byte | 8 bits | Byte data |
| short | 16 bits | Smaller-range integers |
| int | 32 bits | General-purpose integers |
| long | 64 bits | Large-range integers |
The above are the bit widths of common integer types in Java; integer type definitions in other languages may differ.
Signed and Unsigned Integers
Integers can also be divided according to whether they represent negative numbers.
Signed Integer
Can represent negative numbers, zero, and positive numbers.
In the common two's complement representation, the range of an n-bit signed integer is:
For example, the range of an 8-bit signed integer is:
Unsigned Integer
Can represent only zero and positive numbers.
The range of an n-bit unsigned integer is:
For example, the range of an 8-bit unsigned integer is:
| Bit Width | Signed Range | Unsigned Range |
|---|---|---|
| 8-bit | -128 ~ 127 | 0 ~ 255 |
| 16-bit | -32768 ~ 32767 | 0 ~ 65535 |
| 32-bit | -2³¹ ~ 2³¹-1 | 0 ~ 2³²-1 |
| 64-bit | -2⁶³ ~ 2⁶³-1 | 0 ~ 2⁶⁴-1 |
Note:
- Java's primitive integer types do not provide unsigned integer types, with the exception of
char, butcharrepresents a UTF-16 code unit and is not a substitute for an ordinary integer type. - Languages such as C, C++, Go, and Rust provide various forms of unsigned integer types.
- Python integers can expand in precision as needed and are not limited to a fixed 32-bit or 64-bit range.
Integer Overflow
Integer overflow refers to a calculation result exceeding the range that the target integer type can represent.
For example:
int value = Integer.MAX_VALUE;
value = value + 1;
System.out.println(value);
Ordinary integer arithmetic in Java does not automatically throw an overflow exception; here the result wraps around and becomes Integer.MIN_VALUE.
Different languages handle overflow in different ways:
| Language | Common Behavior |
|---|---|
| Java | Ordinary integer arithmetic wraps around at a fixed width |
| C | Signed integer overflow is undefined behavior |
| C++ | Signed integer overflow is undefined behavior |
| Go | Integer arithmetic is handled according to the type width and may wrap around |
| Rust | Depending on the build configuration and the operation, it may check, wrap around, or handle it explicitly |
| Python | Integers automatically expand in precision, limited by available memory |
Integer overflow requires particular attention in financial calculations, counters, index arithmetic, and security-sensitive code.
2. Floating-Point Types
Floating-point numbers are used to represent values with a fractional part.
Common types:
| Type | Common Bit Width | Precision Characteristics |
|---|---|---|
| float | 32-bit | Single precision |
| double | 64-bit | Double precision |
| Extended-precision types | Depends on the implementation | Precision may be higher |
IEEE 754 is the floating-point standard widely adopted in modern computers.
Taking the common IEEE 754 single-precision floating-point number as an example, its 32-bit structure consists of:
- 1 sign bit.
- 8 exponent bits.
- 23 mantissa fraction bits.
Where:
- s: sign bit.
- e: exponent.
- f: mantissa field.
- bias: exponent bias.
Floating-point numbers represent values using the idea of scientific notation, so they can represent very large or very small numbers, but with limited precision.
Floating-Point Precision Issues
For example:
console.log(0.1 + 0.2);
The output may be:
0.30000000000000004
This is because some decimal fractions cannot be represented exactly in binary floating-point format.
Floating-point calculations need to take into account:
- Binary representation error.
- Rounding error.
- Accumulation of precision error.
- Loss of significant digits when adding large numbers and small numbers.
Direct equality comparison of floating-point numbers should not be used for all numerical calculations.
For example:
a = 0.1 + 0.2
b = 0.3
print(abs(a - b) < 1e-9)
For scenarios with strict precision requirements, such as financial amounts, fixed-point or decimal numeric types should generally be used, such as Python's Decimal and Java's BigDecimal.
3. Boolean Type
The Boolean type is used to express logical states and usually has only two values:
truefalse
For example:
boolean isActive = true;
boolean hasPermission = false;
Boolean types are widely used in:
- Conditional checks.
- Loop control.
- Logical expressions.
- State flags.
- Permission validation.
Common logical operations:
| Operation | Meaning | Example |
|---|---|---|
| AND | Logical AND | true && false |
| OR | Logical OR | true || false |
| NOT | Logical NOT | !true |
It is worth noting that the underlying representation of boolean values is not exactly the same across languages.
For example:
- In Java,
booleanis a standalone primitive type. - C uses
_Boolto represent boolean values, andstdbool.hprovides names such asbool. - In Python,
boolis a subclass ofint. - JavaScript uses a standalone Boolean type, and also has rules for converting values to truthy and falsy values.
The logical semantics of a boolean type should not be conflated with its concrete in-memory representation.
4. Character Type (Character)
The character type is used to represent characters or character encoding units in text.
For example, in Java:
char letter = 'A';
However, the underlying representation of characters must be understood in conjunction with character encoding.
ASCII
ASCII uses 7-bit encoding to represent basic Latin characters and control characters, with a total of 128 code values.
Unicode
Unicode assigns code points to the characters of the world, for example:
A: U+0041中: U+4E2D