I. What Are Static and Dynamic Languages?
Statically typed languages and dynamically typed languages are classified mainly by when type checking occurs.
- Statically typed languages: the types of variables, expressions, and so on are usually determined at compile time and checked by the compiler.
- Dynamically typed languages: type information is mainly determined and checked while the program is running, and a variable can refer to objects of different types at different times.
For example:
Java: static typing
int age = 18;
age = "hello"; // Compile error
The variable age is declared as int, so it cannot later be assigned a string directly.
Python: dynamic typing
age = 18
age = "hello" # Valid
In Python, a variable name can be bound to objects of different types at different times.
Note the following:
- Static typing does not mean a variable's value can never change.
- Dynamic typing does not mean there is no type system.
- Static typing is not the same as a compiled language.
- Dynamic typing is not the same as an interpreted language.
These concepts are often confused and need to be understood separately.
II. What Is a Type System?
Before understanding static and dynamic languages, you need to understand type systems.
1. The Essence of Types
A type is an abstract description of data and the operations it permits.
A type usually specifies:
- What kinds of values the data can represent.
- How the data occupies or organizes memory.
- Which operations the data supports.
- Whether different types can be converted into one another.
- What type of result an expression may produce.
For example:
int age = 18;
float price = 19.9;
char grade = 'A';
This defines three different types:
| Type | Meaning | Example |
|---|---|---|
int |
Integer | 18 |
float |
Floating-point number | 19.9 |
char |
Character | 'A' |
Data of different types does not support exactly the same operations.
For example, integers support arithmetic operations, while strings usually support concatenation, slicing, and similar operations.
A type system constrains these operations through rules, reducing unreasonable program behavior.
2. Main Responsibilities of a Type System
A type system usually carries the following responsibilities:
Type constraints
Specify what types variables, function parameters, return values, and expressions may use.
Type checking
Determine whether the operations in a program comply with the type rules.
Type conversion
Specify how conversion between different types is performed.
Type inference
Infer types from expressions, assignment relationships, and context.
Type safety
Prevent operations that violate type rules as far as possible, reducing type errors.
3. The Basic Process of Type Checking
flowchart TB
A["Write source code"] --> B["Identify variables and expressions"]
B --> C["Determine or infer types"]
C --> D["Check type rules"]
D --> E{"Satisfies type constraints?"}
E -->|"Yes"| F["Continue compiling or executing"]
E -->|"No"| G["Report type error"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Statically typed languages usually perform a large amount of type checking at compile time; dynamically typed languages mainly check, at runtime, the types of the objects actually involved in an operation.
III. How Static Languages Work
1. What Is Static Typing?
Static typing means that type information in a program can usually be determined at compile time, so the compiler can check whether the types are valid before the program runs.
For example, Java:
public class Main {
public static void main(String[] args) {
int age = 18;
String name = "Tom";
age = 20;
// age = "hello"; // Compilation error
}
}
At the compilation stage, the compiler can know:
ageis of typeint.nameis of typeString.age = 20conforms to the type rules.age = "hello"does not conform to the type rules.
Therefore, the program can detect some type errors before running.
2. Static Type Checking Process
flowchart TB
A["Source Code"] --> B["Compiler Parsing"]
B --> C["Build Type Information"]
C --> D["Type Inference and Type Checking"]
D --> E{"Is Type Valid?"}
E -->|"Valid"| F["Generate Target Code"]
E -->|"Invalid"| G["Compilation Failed"]
F --> H["Program Execution"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Static type checking can detect in advance:
- Incompatible type assignments.
- Mismatched function parameter types.
- Incorrect return value types.
- Unsupported operations.
- Some issues with the use of null values.
However, static type checking cannot guarantee that a program has no runtime errors. For example, array out-of-bounds, null pointers, network exceptions, and business logic errors can still occur.
3. Static Typing Does Not Mean Explicit Type Declarations Are Required
A common misconception is that statically typed languages require manually specifying the type of every variable.
In fact, modern statically typed languages usually support type inference.
For example, Go:
package main
import "fmt"
func main() {
age := 18
name := "Tom"
fmt.Println(age, name)
}
Although int and string are not explicitly written, the compiler can infer variable types from the initialization expressions.
Now look at TypeScript:
let age = 18;
let name = "Tom";
age = 20;
// age = "hello"; // Type error
TypeScript can automatically infer variable types and detect incompatible assignments during the static checking stage.
Therefore:
Explicit type declarations and static type checking are two different concepts.
Statically typed languages can allow developers to write fewer type annotations, but this does not mean giving up type constraints.
4. Main Characteristics of Statically Typed Languages
- Type errors are detected early: Many type errors can be exposed at the compilation stage.
- Code constraints are clear: Variables, function parameters, and return values have clear type constraints.
- Better tooling support: IDEs can use type information to provide autocompletion, refactoring, and static analysis.
- Large projects are more maintainable: Type declarations can help developers understand interfaces and module boundaries.
- Runtime type-checking overhead may be lower: Some type constraints have already been handled at the compilation stage.
Note that static typing does not necessarily mean there is no type checking at runtime. For example, Java still needs to handle type casting, dynamic dispatch, and runtime type checking.
IV. How Dynamic Languages Work
1. What Is Dynamic Typing?
Dynamic typing means that type information is mainly determined and checked during program execution.
Take Python as an example:
value = 100
print(type(value))
value = "hello"
print(type(value))
value = [1, 2, 3]
print(type(value))
Output:
<class 'int'>
<class 'str'>
<class 'list'>
The variable name value is bound to an integer, then a string, and then a list object.
Here, an important concept needs to be understood:
Dynamic typing usually means that a variable name is not permanently bound to a particular type, not that the object itself has no type.
In Python, an integer object is still an integer object, and a string object is still a string object. What changes is the object referenced by the variable name.
2. Execution Mechanism of Dynamic Typing
Dynamic languages usually obtain type information about objects at runtime and determine whether an operation is valid based on the actual type.
flowchart TB
A["Write source code"] --> B["Parse or compile to intermediate representation"]
B --> C["Run program"]
C --> D["Get runtime type of object"]
D --> E["Perform type-related operations"]
E --> F{"Is operation valid?"}
F -->|"Valid"| G["Continue execution"]
F -->|"Invalid"| H["Throw runtime exception"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
For example:
a = 10
b = "20"
result = a + b
This code can usually pass Python syntax parsing and bytecode compilation, but when execution reaches a + b, a TypeError will be raised because integers and strings do not support this kind of addition operation.
This shows that dynamic languages do not skip type checking; rather, many checks occur during runtime.
3. Main Characteristics of Dynamic Languages
- Flexible type usage: A variable name can be bound to objects of different types at different times.
- Concise development expression: There is usually no need to declare a type for every variable.
- Strong runtime adaptability: Suitable for dynamic data structures, reflection, and flexible extension.
- Some errors are exposed later: Type errors may only be discovered when execution reaches the relevant code path.
- Runtime must handle type information: Some operations require dynamic dispatch, type checking, or method lookup.
Dynamic typing does not mean low code quality, nor does it mean the code will necessarily be difficult to maintain. Sound module design, testing, documentation, and type-checking tools can also build reliable dynamic-language projects.
V. Core Differences Between Static and Dynamic Languages
| Comparison Dimension | Static Languages | Dynamic Languages |
|---|---|---|
| Type Determination | Usually determined at compile time | Mainly determined at runtime |
| Type Checking | Usually primarily compile-time checking | Usually primarily runtime checking |
| Type Declaration | Can be explicitly declared or inferred | Usually does not require explicit declaration |
| Variable Type | Usually constrained by the declared or inferred type | Variable names can be bound to objects of different types |
| Error Detection | Some type errors are discovered in advance | Some type errors are exposed at runtime |
| Development Flexibility | Type constraints are relatively explicit | Type usage is usually more flexible |
| IDE Support | Type information is usually easier to use for static analysis | Relies on inference, annotations, and runtime information |
| Typical Languages | Java, C, C++, Go, Rust, TypeScript | Python, JavaScript, Ruby, PHP |
1. Timing of Error Detection
Static languages can usually detect type mismatch problems before runtime.
Dynamic languages, by contrast, may only discover type errors when the program executes the specific operation.
For example:
Java:
int age = 18;
age = "hello";
The compiler will reject this code.
Python:
age = 18
age = "hello"
print(age)
This code can execute normally.
However:
age = 18
result = age + "hello"
The program will only produce a type error when execution reaches the addition operation.
2. Development Efficiency and Maintenance Cost
Dynamic languages usually have lower initial coding costs.
For example:
def add(a, b):
return a + b
Developers don't need to declare parameter types or return types.
Statically typed languages usually require more type constraints:
public int add(int a, int b) {
return a + b;
}
However, in large projects, type information can become an important maintenance tool.
For example, when changing the parameter type of a shared function, a static type checker can help developers find the call sites affected.
Therefore:
- For small scripts and rapid prototyping, dynamic languages are usually more flexible.
- For large engineering projects and collaboration across complex modules, static typing usually makes it easier to establish clear interface constraints.
- The actual effect also depends on team conventions, the testing regime, and the language toolchain.
6. Static vs. Dynamic Typing Is Not the Same as Compiled vs. Interpreted
This is a very important point in the classification of programming languages.
The two pairs of concepts focus on different questions:
| Classification | Question of Concern |
|---|---|
| Static vs. dynamic typing | When types are determined and checked |
| Compiled vs. interpreted | By what mechanism code is transformed and executed |
There is no necessary correspondence between them.
1. Four Combinations
| Type System | Code Execution Mechanism | Representative Languages |
|---|---|---|
| Static typing | Compiled to machine code | C, C++, Rust, Go |
| Static typing | Compiled to bytecode and executed by a virtual machine | Java, C# |
| Dynamic typing | Interpreted or executed by a virtual machine | Python, Ruby |
| Dynamic typing | Hybrid interpretation and JIT execution | JavaScript |
Note that the execution methods in the table are common implementation forms; they do not mean a language can only use that one implementation.
For example:
- Java is a statically typed language, but it does not simply use the traditional local machine-code compilation and execution model.
- Python is a dynamically typed language, but CPython first compiles source code into bytecode.
- JavaScript is a dynamically typed language, but modern engines make heavy use of JIT compilation.
- TypeScript is a static type-checking toolchain, but it usually erases type information and generates JavaScript, which is then executed by a JavaScript engine.
2. Why Is TypeScript Special?
TypeScript is a typical example for understanding the difference between these two pairs of concepts.
function add(a: number, b: number): number {
return a + b;
}
console.log(add(10, 20));
TypeScript performs static type checking during development and build stages.
But TypeScript code is usually converted into JavaScript.
For example:
function add(a, b) {
return a + b;
}
console.log(add(10, 20));
At runtime, the JavaScript engine does not retain and enforce TypeScript's number type declarations.
Therefore:
- TypeScript provides static type-checking capabilities.
- JavaScript is responsible for the final execution.
- TypeScript's type system mainly serves the development and compilation stages.
- Type information is usually not retained as a runtime enforced constraint.
This is also an important difference between TypeScript and languages such as Java and C# that have runtime type systems.
7. Advanced Type Mechanisms in Statically Typed Languages
Static typing is not just about simply declaring basic types such as int and string. Modern type systems have developed a large number of advanced capabilities.
1. Type Inference
The compiler automatically infers the type of an expression or variable from context.
For example, in Rust: