The process of verifying and enforcing the constraints of types – type checking – may occur either at compile-time (a static check) or run-time (a dynamic check). If a language enforces type rules strongly (that is, generally allowing only those automatic type conversions which do not lose information), one can refer to the process as strongly typed, if not, as weakly typed.
[edit] Static typing
In most compiled computer languages, such as C, C++, Java and Pascal, the data type of every variable, parameter and function return value is known at compile time. The programmer has to provide the type information through declarations. This is known as static typing (but some statically typed languages may include implicit declarations). A programming language is statically typed if type checking may be performed without testing equivalence of run-time expressions. A statically typed programming language respects the distinction between run-time and compile-time phases of processing. A language has a compile-time phase if separate modules of a program can be type checked separately (separate compilation), without information about all modules that exist at run time. Static type-checking becomes a primary task of the semantic analysis carried out by a compiler.
[edit] Dynamic typing
In languages with dynamic data typing, such as Lisp, Perl, Python, Ruby, and JavaScript, type information for data is associated with data rather than the variables through which the data is accessed. Variables may, if needed, refer to data of different types during the execution of a program when necessary. The advantages of dynamic data typing can include more flexibility and quicker development for the programmer. But programmers from a static and manifestly typed language background are used to using data type declarations to help in organizing and understanding a program, and this prop is lost.
In dynamic typing, type checking often takes place at runtime because the value bound to a variable could be of different types dependent on the programs execution path.
To see how dynamic typing works, consider the fileObject parameter and f variable in the following pseudocode example:
// Print the First line of a File
function printFirstLine(fileObject){
print fileObject.getline();
}
f = File(“path”); // return a file object
printFirstLine(f);
f = StringAsFile(“First Line \n More”) // Return a file-like object
printFirstLine(f);
In the first call to printFirstLine, f and fileObject are associated with an instance of File. In the second call they are associated with an instance of StringAsFile. Dynamic typing helps in allowing the one function, printFirstLine, to work reliably with both object types. (Duck typing allows the getline method call to be checked).
Note that the opposite of dynamically typed is statically typed, and is a separate and orthogonal consideration to strong typing/weak typing.