Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java, why new operator not used before data type to allocate memory?

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;
like image 619
user2849331 Avatar asked Nov 02 '14 06:11

user2849331


1 Answers

  1. Because James Gosling said so.... (or Bjarne Stroustrup said so). Really, it is mostly a question of language design, not technical laws.

  2. 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.

like image 191
codenheim Avatar answered Sep 30 '22 12:09

codenheim