Home » Posts tagged 'Type Safety'
Tag Archives: Type Safety
Type safety is prevention of typed errors in a programming language.
A type error occurs when someone attempts to perform an operation on a value that doesn’t support that operation.
In simple words, type safety makes sure that an operation o which is meant to be performed on a data type x cannot be performed on data type y which does not support operation o.
That is, the language will not allow you to to execute o(y).
<!DOCTYPE html> <html> <body> <script> var number = 10; // numeric value var string = "10"; // string value var sum = number + string; // numeric + string document.write(sum); </script> </body> </html>
The output is the concatenation of number and string.
Let’s consider java which is type safe:
You can clearly observe that in java the compiler validates the types while compiling and throwing a compile time exception:
Type mismatch: cannot convert from String to int
As java is type safe, you cannot perform an arithmetic operation between an int and string.
Type-safe code won’t allow any invalid operation on an object and the operation’s validity depends on the type of the object.