Why does Java have a primitive data type?

Possible duplicate:
When we have wrapper classes, why are primitives supported?

If there are Wrapper classes that make Java a purely object oriented language, then why are there primitive data types that can be used in Java ???

+3


source to share


3 answers


For efficiency. Variables of primitive types contain the value directly; variables of non-primitive types are references that refer to an object stored somewhere else in memory.

Every time you need to use a wrapper type value, the JVM needs to look up the object in memory to get the value. This is not required for primitive types, because the variable contains the value itself, not a reference to the object that contains the value.

However, this does not explain why primitive types must be explicitly visible in the Java programming language. The Java and JVM designers could hide primitive types from the language itself so you can treat everything as an object; the compiler can then translate it under the hood to more efficient primitive types.



Some new programming languages ​​that run on the JVM (Groovy, Scala, and others) allow you to do just that: in the language itself, everything looks like an object to which you can, for example, call methods, but below the compiler, which covers them, translates them into primitives.

My guess is that at the time the Java language was developed (in the first half of the 1990s), people didn't think about it, and now it's too late for a radical change in the language to allow it.

+12


source


The main reason for primitive data type is that object creation, heap allocation is too expensive and there is a performance penalty for it. As you may know, primitive data types like int, float, etc. are the most commonly used, so making them objects would be a huge performance hit. So the Java developers thought it would be better to do this as non-objects. And yes, wrappers exist in case you are willing to compromise on performance, but you need more OOP capabilities. So you can use wrappers in this case. Hope this information helps you.



+3


source


For performance reasons. In some other languages, such as SmallTalk, types such as int or char are also objects and methods can be called on them. This is more theoretically correct, but current implementations are slower. Primitive types are a trade-off between purity and performance.

If more is required (null or use with a database), Java provides wrapper classes such as java.lang.Integer, etc.

+2


source







All Articles