What is dynamic typing?
Overview
The term dynamic typing means that a compiler or an interpreter assigns a type to all the variables at run-time. The type of a variable is decided based on its value.
The programs written using dynamic-typed languages are more flexible but will compile even if they contain errors.
Let’s see some examples to understand how dynamic-typed languages differ from static-typed languages.
Example 1
Let’s first see how static-typed languages work:
class Main {public static void main( String args[] ) {int number;number = 10;System.out.println(number);}}
Explanation
In static-typed languages, we have to define the type of a variable before we assign a value to it.
In the code above:
- Line 3: We declare a variable
number. Note that we have also defined its type here. - Line 4: We assign a value to the variable
number. - Line 3: We print the value of the variable
numberon the console.
Example 2
Now let’s see how dynamic-typed languages work:
number = 10print(number)
Explanation
In dynamic-typed languages, we don’t need to define the type of a variable as an interpreter at run-time will handle it.
In the above code:
Line 1: We declare a variable number and assign a value to it. Note that we have not defined its type here.
Line 2: We print the value of variable number on the console.