Primitive vs Object type in Java [duplicate]

坚强是说给别人听的谎言 提交于 2019-11-28 03:19:00

问题


This question came to my mind because I have read somewhere that Java is not a pure Object oriented language since it is using primitives (which are not objects). I can agree with that. Now my problem is why we are using primitives/wrappers while we already have Object in same type?

As an example if we consider Integer, It has same value limit as int other than object behavior. why still Java use primitives under these condition?

As my opinion, if Java only use Object type Autoboxing and Unboxing no need. Also there is no primitive for String by the way.


回答1:


One reason is due to memory usage. Primitives, such as int, float etc. require less memory allocations (I think 4 bytes) in comparison to Objects which are at the very least 8 bytes. Please see the following reference:

In addition, a lot of arithmetic (numeric) is completed with the use of primitives rather than their Object equivalents and this is another reason why they are quite critical in the Java language.



来源:https://stackoverflow.com/questions/18333648/primitive-vs-object-type-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!