← All weekly notes

2 min read

Static and dynamic typing

The difference between when types are checked and how source code is translated for execution.

Programming languages · Type systems · Compilers

Static versus dynamic typing and compiled versus interpreted execution describe two different properties of a programming language. They are related in practice, but one does not determine the other.

What is a type?

A type describes a kind of value and the operations allowed on it. Integers can be added, strings can be joined and a function may require arguments of particular types.

Type checking verifies that a program uses those values consistently.

Static typing

In a statically typed language, types are checked without executing the program, usually during compilation or a separate checking step.

var count int = "five" // Type error before the program runs.

Go, Rust and Java are statically typed. The compiler can reject many invalid operations before the program starts.

Dynamic typing

In a dynamically typed language, values carry type information and checks happen while the program executes.

count = 5count = "five"       # Allowed.result = count + 1   # Type error when this line runs.

Python, Ruby and JavaScript are dynamically typed. A type error may remain unnoticed until execution reaches the relevant path.

What are translation and runtime?

Code translation converts human-readable source code into instructions that a computer or virtual machine can execute.

Runtime is the period when the program is executing those instructions.

  • Compiled: translation happens before execution.
  • Interpreted: an interpreter translates or evaluates code during execution.

Modern languages often combine both approaches. Python compiles source into bytecode before its interpreter executes it. Java compiles to JVM bytecode, which may later be compiled again by a just-in-time compiler.

The important distinction

Static does not mean compiled and dynamic does not mean interpreted. Typing describes when type correctness is checked. Compilation and interpretation describe how code is prepared and executed.

What I want to remember

  • Static typing finds many type errors before execution.
  • Dynamic typing checks operations as execution reaches them.
  • Compilation happens before runtime, while interpretation performs work during runtime.
  • A language can mix these models, so they should be considered separately.