Search code examples
javajavascripttype-safety

Java and Type Safety


The MDN JavaScript guide states the following when doing a comparison between Java and JavaScript:

Type safety means, for instance, that you can't cast a Java integer into an object reference or access private memory by corrupting Java bytecodes.

Sure, regarding the first part of the above statement, when talking about typing the general concept of type safety revolves around a languages ability to provide some kind of checking that eliminates possible erroneous conditions regarding operations performed with incompatible types (even though the above example is naive considering that in Java you can box primitive int to the reference type Integer).

But, what exactly do they mean by the second part of the statement?

Here there is talk about the JVM's verifier ensuring a level of memory protection - where "arbitary bit patterns cannot be used as an address."

How does the second part of the statement from MDN relate to type safety?


Solution

  • It means that in Java, there is (in principle) no way to get around how types are identified. In javascript, a type can be inferred based on how the byte sequence that represents a piece of data. In Java, the VM prevents that sort of thing, to ensure that a sequence of bytes that is intended to be a Foo object, can not be seen as a Bar object.

    About accessing private members, that means that you can't make a sequence of bytes mean something different than intended by the programmer, to obtain access to something unintended. At runtime, you can't change object foo of type Foo with private member foobar into an object of type Bar, with the same members, but with foobar made public. The type of each object is encoded in the byte code, which is controlled by the VM at runtime.