Back to series
· 11 min read

Data Types


I. What Is a Data Type?

A data type is an abstract description of data in a programming language, used to define what values a category of data can hold, how it is represented, and which operations are permitted on it.

For example:

age = 25
price = 19.99
name = "Reverie"
is_active = True

These variables use the integer, floating-point, string, and boolean types, respectively.

A data type is not merely a label attached to data; it usually involves the following aspects:

Dimension Meaning Example
Value range Which values the data can represent Integers, finite-precision floating-point numbers
Storage representation How the data is encoded in memory Two's complement, IEEE 754
Operation set Which operations the data permits Addition, subtraction, multiplication, division; string concatenation
Type rules Which operations are legal and which are not Whether an integer and a string can be added
Type checking How type errors are detected Compile-time checking, run-time checking

You can think of a data type as:

Data type = set of values + set of operations + type rules

Note that different programming languages may define and implement data types differently. The same concept may have different value ranges, precision, memory layouts, and type-checking behavior in different languages.

II. Why Do We Need Data Types?

At the lowest level, computers process binary data. The same set of binary bits can represent completely different values depending on how it is interpreted.

For example, the following 8-bit binary data:

00000101

can be interpreted as:

  • An unsigned integer: 5
  • A signed integer: 5
  • A character encoding: depending on the character encoding standard used
  • One byte within another data structure: depending on the specific protocol and context

Binary data itself does not inherently carry complete business meaning. Data types provide the interpretation rules for these bits.

2.1 Clarifying the Meaning of Data

Data types allow a program to distinguish between data of different natures.

For example:

count = 10
message = "10"

Although both variables appear to contain 10, their semantics differ:

  • count represents a numeric value and can take part in mathematical operations.
  • message represents text and can take part in string concatenation.
print(count + 5)       # 15
print(message + "5")   # "105"

2.2 Constraining Data Operations

Data types define which operations data can participate in.

For example:

age = 25
name = "Alice"

print(age + 10)
print(name + " Smith")

Integers can undergo numeric operations, and strings can be concatenated.

If you attempt an operation that does not conform to the language's rules, the program may produce a type error at compile time or at run time.

2.3 Providing Memory Representation Rules

Data types usually affect how data is stored, its size, its alignment, and the rules for interpreting it.

For example, in a common C implementation:

int age = 25;
float price = 19.99f;
char grade = 'A';

Different types typically use different memory representations.

Note, however, that the C standard does not guarantee that int and float have exactly the same number of bytes on all platforms. The specific sizes depend on the implementation.

2.4 Improving Program Reliability

Type checking can detect some errors in advance or in a timely manner.

For example:

let age: number = 25;

age = "twenty-five";

TypeScript will report a type mismatch during the static type-checking phase.

A type system cannot guarantee that a program is free of errors, but it can narrow the error space and allow some problems to be caught before the program runs.

III. Main Categories of Data Types

Different programming languages do not classify types in exactly the same way.

From the perspective of basic data structures and language design, common data types can be divided into the following categories:

flowchart TB
    A["Data Types"] --> B["Primitive Types"]
    A --> C["Composite Types"]
    A --> D["Special Types"]

    B --> B1["Integer Types"]
    B --> B2["Floating-Point Types"]
    B --> B3["Boolean Types"]
    B --> B4["Character Types"]

    C --> C1["Arrays"]
    C --> C2["Structs"]
    C --> C3["Classes and Objects"]
    C --> C4["Tuples"]
    C --> C5["Sets and Maps"]

    D --> D1["Null Type"]
    D --> D2["Pointer Types"]
    D --> D3["Reference Types"]
    D --> D4["Function Types"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style B1 fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style B2 fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style B3 fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style B4 fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C1 fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C2 fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C3 fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C4 fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C5 fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style D1 fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D2 fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style D3 fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style D4 fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

This is a conceptual classification intended to make things easier to understand; not all languages use the same classification system.

4. Basic Data Types

Primitive data types (Primitive Types) are usually the basic types provided directly by a language, used to represent the most common data.

4.1 Integer Types (Integer)

Integer types are used to represent numeric values without a fractional part.

Common integers include:

-100
-1
0
1
100

Common integer types:

Type Meaning
int8 8-bit signed integer
int16 16-bit signed integer
int32 32-bit signed integer
int64 64-bit signed integer
uint8 8-bit unsigned integer
uint16 16-bit unsigned integer
uint32 32-bit unsigned integer
uint64 64-bit unsigned integer

For an n-bit integer:

Range of unsigned integers:

0 \leq x \leq 2^n-1

Range of signed integers when using two's complement:

-2^{n-1} \leq x \leq 2^{n-1}-1

For example:

Type Value Range
int8 -128 ~ 127
uint8 0 ~ 255
int16 -32768 ~ 32767
uint16 0 ~ 65535

The number of bits in an integer determines the range it can represent.

Integer Overflow

Integer overflow can occur when a calculation result exceeds the range that a type can represent.

For example, the maximum value of an 8-bit unsigned integer is 255:

255 + 1

In an unsigned integer model that uses modulo 2^8 arithmetic, the result wraps around to:

0

However, this behavior cannot be generalized to all integer types and languages.

For example:

  • In C, unsigned integer overflow is handled using modulo arithmetic.
  • In C, signed integer overflow is undefined behavior.
  • In Java, integer arithmetic overflow preserves the low-order bits and produces a wrapped-around result.
  • Python integers can automatically expand their precision, up to resource limits such as available memory.

Therefore, when handling integer overflow, you must take the specific language's specification into account.

4.2 Floating-Point Type (Floating-Point)

Floating-point numbers are used to represent values with a fractional part, as well as approximate values over larger or smaller ranges.

Common types:

Type Common precision Typical use
float32 Single precision, approximately 7 decimal significant digits Graphics computing, general numerical computing
float64 Double precision, approximately 15–16 decimal significant digits Scientific computing, general-purpose numerical computing

Many languages use the IEEE 754 standard to define the representation and arithmetic behavior of floating-point numbers.

Take a 32-bit single-precision floating-point number as an example:

1 sign bit
8 exponent bits
23 mantissa bits

Floating-point numbers can represent a very large range of values, but they cannot exactly represent all real numbers.

For example:

print(0.1 + 0.2)

may produce:

0.30000000000000004

The reason is that decimal 0.1 and 0.2 cannot be exactly represented as finite-length binary fractions.

The core characteristics of floating-point numbers are:

  • They have a large representation range.
  • They have limited precision.
  • Arithmetic operations may produce rounding errors.
  • They are not suitable for direct use in financial calculations that require strict decimal precision.

For business data such as monetary amounts, consider using decimal fixed-point numbers, integer minor currency units, or a dedicated Decimal type.

Special Floating-Point Values

IEEE 754 floating-point numbers also define several special values:

Special value Meaning
+Infinity Positive infinity
-Infinity Negative infinity
NaN Not a number
+0 Positive zero
-0 Negative zero

Among them, NaN has special comparison rules:

x = float("nan")

print(x == x)  # False

Therefore, to test for NaN, you should generally use a dedicated detection function rather than directly comparing it with itself.

4.3 Boolean Type (Boolean)

The Boolean type is used to represent logical states and usually has only two values:

True
False

For example:

is_login = True
is_admin = False

The Boolean type is widely used for:

  • Condition checks
  • Loop control
  • Logical operations
  • State representation
  • Permission checks

Common logical operations:

Operation Meaning
AND Logical AND
OR Logical OR
NOT Logical NOT

For example:

age = 25
is_member = True

if age >= 18 and is_member:
    print("允许访问")

Note that the underlying representation of Boolean values is not necessarily the same in different languages.

For example, C uses the _Bool type, and logical values are usually represented as 0 and 1; in Python, bool is a subclass of int; JavaScript has a separate boolean type.

4.4 Character Type (Character)

The character type is used to represent a single character.

For example:

'A'
'中'
'7'

Different languages have clearly different definitions of the character type.

Language Character representation
C char, typically used to store one byte
Java char, uses 16-bit UTF-16 code units
Go rune, represents a Unicode code point, underlying type is int32
Python No separate single-character type; a single character is still a string

Three concepts need to be distinguished:

  • Byte: usually an 8-bit data unit.
  • Unicode Code Point: the number assigned to a character by Unicode.
  • User-perceived character (Grapheme Cluster): a complete character as seen by the user, which may consist of multiple code points.

For example, a character with combining diacritical marks may consist of multiple Unicode code points.

Therefore, a character is not necessarily equal to one byte, nor necessarily equal to one Unicode code point.

5. Composite Data Types

Composite Types are composed of multiple data elements and are used to express more complex data structures.

5.1 Array

An array is a data structure composed of multiple elements of the same type or constrained by specific type rules.

For example:

int numbers[5] = {10, 20, 30, 40, 50};

Arrays usually have the following characteristics:

  • Elements are arranged in a certain order.
  • Elements can be accessed by index.
  • In fixed-length arrays, the length is usually determined at creation.
  • Array elements usually have the same type.

Typical memory layout of an array:

flowchart LR
    A["Array numbers"] --> B["Index 0"]
    A --> C["Index 1"]
    A --> D["Index 2"]
    A --> E["Index 3"]

    B --> F["10"]
    C --> G["20"]
    D --> H["30"]
    E --> I["40"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style H fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

The advantage of arrays is that elements are usually stored contiguously, allowing fast location by index.

However, arrays are not entirely the same across languages. For example, C arrays differ greatly from JavaScript dynamic arrays and Python's list in memory layout and type constraints.

5.2 Struct

A struct is used to combine multiple data of different types into a single whole.

For example:

struct User {
    int id;
    char name[32];
    int age;
};

A user object may contain:

  • User ID
  • User name
  • User age

Structs are suitable for representing entities with multiple attributes.

The memory layout of a struct is affected by factors such as member order, alignment requirements, and padding bytes.

For example:

struct Example {
    char a;
    int b;
};

Even though char occupies only one byte, the entire struct does not necessarily occupy only five bytes. The compiler may insert padding bytes to satisfy the alignment requirements of int.

5.3 Class and Object

In object-oriented languages, classes are usually used to define the attributes and behavior of objects.

For example:

class User {
    int id;
    String name;

    void login() {
        System.out.println("User login");
    }
}

Creating an object:

User user = new User();
user.id = 1001;
user.name = "Alice";

Both classes and structs can combine multiple data members, but their language semantics and capabilities are not the same.

Classes usually also involve:

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Method dispatch
  • Object lifecycle

Note that whether a class is a reference type and how objects are allocated in memory depend on the specific language. For example, Java class instances are usually accessed through references, while C++ class objects can be stored directly or accessed through pointers or references.

5.4 Tuples (Tuple)

A tuple is used to combine multiple values of different types together.

For example:

user = (1001, "Alice", 25)

It can contain:

  • An integer
  • A string
  • An integer

Tuples are commonly used for:

  • Returning multiple values
  • Temporarily grouping data
  • Passing function arguments
  • Expressing structured data

In Python, tuples are usually immutable; in other languages, the mutability and type rules of tuples may differ.

5.5 Sets and Maps (Set and Map)

Sets and maps are used to express different ways of organizing data.

Set (Set)

A set usually stores non-duplicate elements:

numbers = {1, 2, 3, 4}

Main characteristics:

  • Elements are usually unique.
  • Suitable for membership tests.
  • The order of elements is not necessarily guaranteed.

Map (Map)

A map organizes data using key-value pairs:

user = {
    "id": 1001,
    "name": "Alice",
    "age": 25
}

Each element in a map consists of a key and a value.

Common names include:

Language Map type
Python dict
Java Map
Go map
JavaScript Map, plain objects
Rust HashMap

The underlying implementation of sets and maps may use hash tables, trees, or other data structures; the specific performance characteristics depend on the implementation.

Six. Special Data Types

In addition to primitive types and composite types, programming languages also provide many types for expressing special semantics.

6.1 Null Value Types (Null / None / Nil)

A null value is used to represent a missing value, the absence of an object, or some special empty state.

Different languages use different representations:

Language Null representation
Python None
Java null
JavaScript null, undefined
Go nil
Rust Usually expresses optional values through Option

It is necessary to distinguish between:

  • Empty string: ""
  • Numeric zero: 0
  • Boolean false: false
  • Null value: null or the corresponding null representation in the language

They are not the same concept.

For example:

let a = "";
let b = 0;
let c = false;
let d = null;
let e;

console.log(a === null); // false
console.log(b === null); // false
console.log(c === null); // false
console.log(d === null); // true
console.log(e === undefined); // true

Handling null values is a very important boundary issue in real-world development.

6.2 Pointer Types (Pointer)

A pointer is used to store the memory address where another object or piece of data resides.

For example, in C:

int age = 25;
int *ptr = &age;

Where:

  • age is an integer variable.
  • &age is the address of the variable.
  • ptr stores that address.
  • *ptr accesses the corresponding value through the pointer.

The core relationship of pointers:

flowchart LR
    A["Pointer variable ptr"] --> B["Memory address"]
    B --> C["Variable age"]
    C --> D["Value 25"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

Pointers are an important concept for understanding low-level programming, involving:

  • Memory addresses
  • Pointer arithmetic
  • Dynamic memory allocation
  • Null pointers
  • Wild pointers
  • Dangling pointers
  • Memory safety

Pointers are not equivalent to references. The two may differ significantly in language semantics, operational capabilities, and safety constraints.

6.3 Reference Type

References are typically used to indirectly access an object or data.

For example, in Java:

User user = new User();

Here, user is a reference variable used to access a User object.

References and pointers have similarities, but they are not exactly the same:

Comparison aspect Pointer Reference
Whether it indirectly accesses data Yes Yes
Whether it can be null Depends on the language Depends on the language
Whether the target can be changed Usually yes Depends on the language
Whether it supports address arithmetic Supported in some languages Usually not supported
Safety constraints Depends on the language Depends on the language

Particular attention should be paid to the fact that Java references, C++ references, and Rust references are not exactly the same concept.

It cannot simply be assumed that all references are syntactic wrappers around pointers.

6.4 Function Type

Functions themselves can also serve as a type.

A function type typically describes:

  • Parameter types
  • Return value type
  • Calling conventions or other constraints

For example, in TypeScript:

type AddFunction = (a: number, b: number) => number;

const add: AddFunction = (a, b) => {
    return a + b;
};

Here, AddFunction describes a function type that takes two numbers and returns a number.

Function types are an important foundation for techniques such as functional programming, higher-order functions, callback mechanisms, and dependency injection.

VII. Static Typing and Dynamic Typing

Data type classification can also be understood in terms of when type checking occurs.

This is also a very important set of concepts in programming languages.

7.1 Static Typing

Statically typed languages usually perform type checking during compilation or another analysis phase before program execution.

For example, in Java:

int age = 25;
age = "Alice"; // Compile error

The compiler can detect type mismatches before the program runs.

Common statically typed languages:

  • C
  • C++
  • Java
  • Go
  • Rust
  • TypeScript (static analysis via a type checker)

Advantages of static typing:

  • It can detect some type errors in advance.
  • It facilitates code refactoring and tool-based analysis.
  • Type information helps IDEs provide autocompletion.
  • It makes complex data constraints easier to express.

However, static typing does not mean that all errors can be found at compile time, nor does it mean that type issues are completely absent at runtime.

7.2 Dynamic Typing

Dynamically typed languages usually determine or check the types of objects during program execution.

For example, in Python: