Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no primitive type for String? [duplicate]

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

like image 407
user241924 Avatar asked Jan 20 '10 05:01

user241924


People also ask

Why is there no primitive type for string in Java?

Because a string is an array of characters, it is a composite type.

Why are strings not primitive data types?

String is non-primitive because only class can have methods. Primitive can not. And String need many functions to be called upon while processing like substring, indexof, equals, touppercase. It would not have been possible without making it class.

Why are primitives not allowed in collections?

++ 1) collections requires objects for manipulation and primitives are not derived from object so this can be the other reason. 2) Java primitive data types are not reference type for ex. int is not an object.

Is string a non-primitive data type?

The string data type is a non-primitive data type but it is predefined in java, some people also call it a special ninth primitive data type. This solves the case where a char cannot store multiple characters, a string data type is used to store the sequence of characters.


1 Answers

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.

like image 52
Jon Avatar answered Oct 08 '22 01:10

Jon