If we need new
operator to allocate the memory for an object, then why don't we use it
before data types to allocate the memory?
class-name class-var = new class-name();
new int a;
Because James Gosling said so.... (or Bjarne Stroustrup said so). Really, it is mostly a question of language design, not technical laws.
javac
hides these semantics from you and does what is called boxing / unboxing (and does it automatically). Those types can exist as values
or as "objects" (typically implemented with a heap). When a context requires an object reference, javac emits a box instruction to move the int
value into an object wrapper (int -> Integer) and passes a reference value
. Many low level JVM opcodes are built to handle scalar values as are some built to handle reference values (or just references).
One prime example is storing an int
into a collection. It gets boxed.
But in the end, asking why a language does what it does syntactically is just like asking an artist why he painted a painting thus. Just because. Languages are designed somewhat by whim and emotion, but in Java's case, the syntax of new
was inherited from C++ so the whim might have been Bjarne Stroustrup's instead. Also consider that Scala is also a JVM language, yet it has very different syntax for some common ideas.
The key here is the compiler writer can make a decision tomorrow that "NEW Java" will be a new language that requires NEW
in all caps in front of all types. It could be implemented without affecting the semantics of the language, whatsoever.
Granted, there is sound design and consistency behind the choices, but the choices are still just choices. In this case, the choice clearly indicates that an int
is a primitive type, and new
only returns objects, not primitives. So it is a good choice of syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With