Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are all objects created dynamically in java? [closed]

Tags:

java

object

In an interview I was asked why are objects in java created dynamically?

I can't understand this question, can any body explain this?

like image 519
user2783700 Avatar asked Oct 03 '22 22:10

user2783700


2 Answers

The person could be referring to the fact that Java does not know implicit object creation on the stack like C++ does.

std::string string;

Creates an object on the stack in C++ while

String string;

just creates a reference in Java, but no object is created (and no constructor called).

If you are interested about that topic I suggest to read more about Java's memory model.

like image 64
Jan Henke Avatar answered Oct 07 '22 20:10

Jan Henke


It seems to me that the question asks why objects in Java are created only with dynamically allocated memory (using the new keyword) as opposed to being created with statically allocated memory as well (like in C++, for example). If (and it's a big if) this is what the question meant, there are some things you can answer to that.

Before answering, one must note that the premise of the question is not entirely right (you could even say that it's wrong). Java objects aren't created strictly dynamically. If escape analysis can prove that a reference doesn't escape a given scope, it may be compiled so that it uses static allocation.

Given the above, one possible answer is abstraction. The stack and the heap (which are traditionally associated with static and dynamic memory, respectively) are in fact implementation details (even if we are so used to them). Java attempts to hide that and thus it doesn't give you terms like static or dynamic memory to work with - it doesn't even give you memory, it gives you objects.

Another answer (again, given the note) is the real world usage of objects. A lot of the time in real world scenarios, objects do need to escape their initial scope, making dynamic allocation the only valid candidate.

like image 33
Theodoros Chatzigiannakis Avatar answered Oct 07 '22 18:10

Theodoros Chatzigiannakis