Is String a Primitive Type

Is String a primitive type?

Both articles say that string is NOT a primitive type. Which it is not.

If you compile and run the example code from the second article it would print:

string is not a primitive type.

I think the confusion about this is, that the syntax of of creating a new string is similar to creating value types.

When defining a value type all of these are equal (on a 32 bit system anyway)

System.Int32 a = new System.Int32(5);
System.Int32 a = 5;
int a = 5;

Just like these when creating a reference type string:

System.String s = new System.String(new char[]{'h', 'e', 'l', 'l', 'o'});
System.String s = "hello";
string s = "hello";

Also we can compare strings by value even though they are reference types:

s == "hello";//true

This still does not make string a primitive type.

The accepted answer to this question should give you details on that.

Disagreement about string is a primitive type

There are language primitive Torres and there are CLR primitive types. Language primitive types are types that are tested special by the compiler itself, like string and dynamic. CLR primitive types are the core building blocks of other types, like Boolean or Int32. The reflection function IsPrimitive returns true for CLR primitive types only, it doesn't know what programming language you used to write your code so it can't know about language primitive types. The only way to know which types are language primitive types is to read the language specification document. As pointed out, in C#, dynamic is a C# primitive type because the compiler tests it special (it allows special casting rules and dynamic member invocations with it). However, the compiler turns dynamic into Object at runtime. There is no dynamic type that the CLR knows about at all.

Why is there no primitive type for String?

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.

Is String a primitive or an Object in Android or Java?

As far as Java programming language is considered,

A primitive type is predefined by the language and is named by a reserved keyword.

In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class.

—— from The Java™ Tutorials - Primitive Data Types

So, as such in Java books, it's not a keyword and not a primitive either. SharedPreferences may still call it one of the primitives, but that's not from the book of Java as such, it could be because it's one of the set of basic types like int, float, char etc we come across.

In Java, Why String is non-primitive data type?

String str = “This is string literal”;

This is string literal. When you declare string like this, you are actually calling intern() method on String. This method references internal pool of string objects. If there already exists a string value “This is string literal”, then str will reference of that string and no new String object will be created.

String str = new String(“this is string created by new operator”);

This is string object. In this method JVM is forced to create a new string reference, even if “this is string created by new operator” is in the reference pool.

Why is the string literal considered a primitive type in JavaScript?

Fundamentally, because the specification says so:

string value

primitive value that is a finite ordered sequence of zero or more 16-bit unsigned integer values

The specification also defines that there are String objects, as distinct from primitive strings. (Similarly there are primitive number, boolean, and symbol types, and Number and Boolean and Symbol objects.)

Primitive strings follow all the rules of other primitives. At a language level, they're treated exactly the way primitive numbers and booleans are. For all intents and purposes, they are primitive values. But as you say, it would be insane for a = b to literally make a copy of the string in b and put that copy in a. Implementations don't have to do that because primitive string values are immutable (just like primitive number values). You can't change any characters in a string, you can only create a new string. If strings were mutable, the implementation would have to make a copy when you did a = b (but if they were mutable the spec would be written differently).

Note that primitive strings and String objects really are different things:

const s = "hey";const o = new String("hey");
// Here, the string `s` refers to is temporarily// converted to a string object so we can perform an// object operation on it (setting a property).s.foo = "bar";// But that temporary object is never stored anywhere,// `s` still just contains the primitive, so getting// the property won't find it:console.log(s.foo); // undefined
// `o` is a String object, which means it can have propertieso.foo = "bar";console.log(o.foo); // "bar"

Are Int, String etc. considered to be 'primitives' in Swift?

Yes and no...

As other answers have noted, in Swift there's no difference at the language level between the things one thinks of as "primitives" in other languages and the other struct types in the standard library or the value types you can create yourself. For example, it's not like Java, where there's a big difference between int and Integer and it's not possible to create your own types that behave semantically like the former. In Swift, all types are "non-primitive" or "user-level": the language features that define the syntax and semantics of, say, Int are no different from those defining CGRect or UIScrollView or your own types.

However, there is still a distinction. A CPU has native instructions for tasks like adding integers, multiplying floats, and even taking vector cross products, but not those like insetting rects or searching lists. One of the things people talk about when they name some of a language's types "primitively" is that those are the types for which the compiler provides hooks into the underlying CPU architecture, so that the things you do with those types map directly to basic CPU instructions. (That is, so operations like "add two integers" don't get bogged down in object lookups and function calls.)

Swift still has that distinction — certain standard library types like Int and Float are special in that they map to basic CPU operations. (And in Swift, the compiler doesn't offer any other means to directly access those operations.)

The difference with many other languages is that for Swift, the distinction between "primitive" types and otherwise is an implementation detail of the standard library, not a "feature" of the language.


Just to ramble on this subject some more...

When people talk about strings being a "primitive" type in many languages, that's a different meaning of the word — strings are a level of abstraction further away from the CPU than integers and floats.

Strings being "primitive" in other languages usually means something like it does in C or Java: The compiler has a special case where putting something in quotes results in some data getting built into the program binary, and the place in the code where you wrote that getting a pointer to that data, possibly wrapped in some sort of object interface so you can do useful text processing with it. (That is, a string literal.) Maybe the compiler also has special cases so that you can have handy shortcuts for some of those text processing procedures, like + for concatenation.

In Swift, String is "primitive" in that it's the standard string type used by all text-related functions in the standard library. But there's no compiler magic keeping you from making your own string types that can be created with literals or handled with operators. So again, there's much less difference between "primitives" and user types in Swift.

In Java, why can we use the String class as if it were a primitive?

...as if String were a primitive?

As Jon points out in a comment, "has a literal form" != "is a primitive type." :-) Strings have a literal form in Java because the spec defines one for them. String is still an object type.

Some languages have other object types that also have literal forms (JavaScript, for instance, has literal forms for regular expressions, arrays, and non-array objects [its literal form for strings does actually define what it calls a string primitive rather than string object — JavaScript has both primitive and object versions of strings]). I think strings are the only one in Java (other than null, which is the literal for "no object"), although of course there are array initializers, which are similar but not quite the same as literals.

So is string object type or primitive type?

Strings are primitive values:

4.3.2 primitive value

member of one of the types Undefined, Null, Boolean, Number, or String

But there are also string objects, which are objects and not primitives:

4.3.18 String object

member of the Object type that is an instance of the standard built-in
String constructor

It may seem primitive strings have properties, but no.

When you use for example string.charAt(0), a string object is created with the same value as your primitive string. This object inherits from String.prototype. The charAt method of this string object is called, and the returned value is returned in string.charAt(0). Then the string object is removed.

When you assign a property to a primitive string, something similar happens: the property is assigned to the new string object instead of to the primitive.

Some examples:

var primitiveStr = 'foo',
objectStr = new String('foo');
typeof primitiveStr; // 'string'
typeof objectStr; // 'object'
typeof primitiveStr.charAt; // 'function'
typeof objectStr.charAt; // 'function'
primitiveStr.foo = objectStr.foo = 123;
typeof primitiveStr.foo; // 'undefined'
typeof objectStr.foo; // 'number'


Related Topics



Leave a reply



Submit