Search code examples
variablestypesdynamic-languagesstatic-typing

Does static typing mean that you have to cast a variable if you want to change its type?


Are there any other ways of changing a variable's type in a statically typed language like Java and C++, except 'casting'?

I'm trying to figure out what the main difference is in practical terms between dynamic and static typing and keep finding very academic definitions. I'm wondering what it means in terms of what my code looks like.


Solution

  • Make sure you don't get static vs. dynamic typing confused with strong vs. weak typing.

    • Static typing: Each variable, method parameter, return type etc. has a type known at compile time, either declared or inferred.
    • Dynamic typing: types are ignored/don't exist at compile time
    • Strong typing: each object at runtime has a specific type, and you can only perform those operations on it that are defined for that type.
    • Weak typing: runtime objects either don't have an explicit type, or the system attempts to automatically convert types wherever necessary.

    These two opposites can be combined freely:

    • Java is statically and strongly typed
    • C is statically and weakly typed (pointer arithmetics!)
    • Ruby is dynamically and strongly typed
    • JavaScript is dynamically and weakly typed

    Genrally, static typing means that a lot of errors are caught by the compiler which are runtime errors in a dynamically typed language - but it also means that you spend a lot of time worrying about types, in many cases unnecessarily (see interfaces vs. duck typing).

    Strong typing means that any conversion between types must be explicit, either through a cast or through the use of conversion methods (e.g. parsing a string into an integer). This means more typing work, but has the advantage of keeping you in control of things, whereas weak typing often results in confusion when the system does some obscure implicit conversion that leaves you with a completely wrong variable value that causes havoc ten method calls down the line.