Junior
What is the difference between dynamic and static typing?
sobes.tech AI
Answer from AI
Dynamic typing: the variable's type is determined at runtime. The same variable can hold data of different types.
Static typing: the variable's type is determined during compilation (or interpretation before execution). After declaration, the variable can only hold data of a specific type.
Main differences:
| Attribute | Dynamic Typing | Static Typing |
|---|---|---|
| Type Definition | During runtime | During compilation/analysis |
| Flexibility | High, variables can change type | Low, fixed type |
| Error Detection | During runtime | During compilation/analysis |
| Performance | May be lower (due to checks during execution) | May be higher (due to compiler optimizations) |
| Language Examples | Python, Ruby, JavaScript | Java, C++, C#, Go |
Example in Python (dynamic):
# age starts as an integer
age = 30
print(type(age))
# age now a string
age = "thirty"
print(type(age))
Example in Java (static):
// age declared as int and can only hold integers
int age = 30;
// String age = "thirty"; // Compilation error