In an interview I was asked why are objects in java created dynamically?
I can't understand this question, can any body explain this?
In an interview I was asked why are objects in java created dynamically?
I can't understand this question, can any body explain this?
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.
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.
A very open-ended question, some context is required to give a good answer.
It's not specific to Java, but to all programming languages in general. Every object can be though of as dynamic, as memory allocated for an object, is allocated in run-time, from the resources available on the executing platform. Even constants, static classes and similar concepts use memory only when a file was actually executed.
Static objects may exist in some hardware hardcoded values, such as some parts of BIOS ot TPL module. This values are read-only - there is no known way to change the values of the object.
However, this is only a single answer that depends on what I think dynamic means. It is subjective and different people may come up with other valid answers. It's not a good question for an interview, unless some additional context was given.
If you take the question literall i would say:
So you dont have to load everything at once (on the init fase) and keep it in the memory till the end of the app/program. which gives you a more efficient memory usage.
;-)