Question

This question already has an answer here:

Why doesn't Java have a primitive type for String when most of the other data types do?

Was it helpful?

Solution

String is an object, it isn't a primitive type at all, just an array of chars. The reason why primitive types exist in Java at all is an interesting one, excerpt from a James Gosling interview:

Bill Venners: Why are there primitive types in Java? Why wasn't everything just an object?

James Gosling: Totally an efficiency thing. There are all kinds of people who have built systems where ints and that are all objects. There are a variety of ways to do that, and all of them have some pretty serious problems. Some of them are just slow, because they allocate memory for everything. Some of them try to do objects where sometimes they are objects, sometimes they are not (which is what the standard LISP system did), and then things get really weird. It kind of works, but it's strange.

Just making it such that there are primitive and objects, and they're just different. You solve a whole lot of problems.

So in short the primitive types exist for efficiency reasons.

OTHER TIPS

int, char, float, double, etc. all have a fixed length in memory. e.g. a int have 4 bytes, thus 32bits.

but a string can have different length, it is actually an array of char.

Most programming languages don't consider a string primitive because it's actually an array of characters. Primitive types almost always have a fixed size.

I should say though that some people might consider String to be "primitive" because it is built-in. But it's not primitive in the sense of being a basic type as opposed to a composite type. Because a string is an array of characters, it is a composite type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top