Strongly typed and Weakly typed programming explained!
Differences between strongly typed and weakly typed programming
📌Strongly typed vs weakly typed:
In strongly typed languages you get an error if the types do not match in an expression. It does not matter if the type is determined at compile time (static types) or runtime (dynamic types).
Both java and python are strongly typed. In both languages, you get an error if you try to add objects with unmatching types. For example, in python, you get an error if you try to add a number and a string:
>>> a = 10
>>> b = "hello"
>>> a + b
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
In Python, you get this error at runtime. In Java, you would get a similar error at compile time. Most statically typed languages are also strongly typed.
The opposite of strongly typed language is weakly typed. In a weakly typed language, there are implicit type conversions. Instead of giving you an error, it will convert one of the values automatically and produce a result, even if such conversion loses data. This often leads to unexpected and unpredictable behavior.
Javascript is an example of a weakly typed language.
> let a = 10
> let b = "hello"
> a + b
'10hello'
Instead of an error, javascript will convert variable a to string and then concatenate the strings.
📌Static types vs Dynamic types:
In a statically typed language, variables are bound types and may only hold data of that type. Typically you declare variables and specify the type of data that the variable has. In some languages, the type can be deduced from what you assign to it, but it still holds that the variable is bound to that type. For example, in java:
int a = 3;
a = "hello" // Error, variable a can only contain integers
In a dynamically typed language, variables may hold any type of data. The type of the data is simply determined by what gets assigned to the variable at runtime. Python is dynamically typed, for example:
a = 10
a = "hello"
# no problem, variable a first held an integer and then a string
Thanks for reading. Let me know what you think in the comment section. If you love to see more educating articles then a sub to the blog would be