Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why are there Primitive datatype in Java? [duplicate]

Possible Duplicate:
When we have wrappers classes, why primitives are supported?

If there are Wrapper classes which make Java pure object-oriented language, then why are there Primitive datatypes which can be used in Java???

like image 382
user2003432 Avatar asked Jan 23 '13 10:01

user2003432


People also ask

Why does Java provide 8 primitive data types?

Primitive types are the most basic data types available within the Java language. There are 8: boolean , byte , char , short , int , long , float and double . These types serve as the building blocks of data manipulation in Java. Such types serve only one purpose — containing pure, simple values of a kind.

Are doubles primitive type in Java?

Primitive Data Types. The eight primitives defined in Java are int, byte, short, long, float, double, boolean and char.

Are doubles primitive data types?

Primitive data types - includes byte , short , int , long , float , double , boolean and char.

Why primitive data types are not used in ArrayList?

ArrayList accepts only reference types as its element, not primitive datatypes. When trying to do so it produces a compile time error.


1 Answers

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

Each time you need to use the value of a wrapper type, the JVM needs to lookup the object in memory to get at the value. This isn't needed for primitive types, because the variable contains the value itself, instead of a reference to an object that contains the value.

However, that doesn't explain why primitive types need to be explicitly visible in the Java programming language. The designers of the Java language and the JVM could have chosen to hide primitive types from the language itself, so that you could treat everything as an object; the compiler could then translate it under the covers to more efficient primitive types.

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

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

like image 192
Jesper Avatar answered Oct 27 '22 23:10

Jesper