String is primitive type in java

Is string a primitive data type in java

Solution: Fundamentally, because the specification says so: The specification also defines that there are String objects, as distinct from primitive strings. Note that primitive strings and String objects really are different things:

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 properties o.foo = "bar"; console.log(o.foo); // "bar"

So why have primitive strings? You’d have to ask Brendan Eich (and he’s reasonably responsive on Twitter), but I suspect it was so that the definition of the equivalence operators ( == , === , != , and !== ) didn’t have to either be something that could be overloaded by an object type for its own purposes, or special-cased for strings.

Читайте также:  Javascript код символа ascii

So why have string objects? Having String objects (and Number objects, and Boolean objects, and Symbol objects) along with rules saying when a temporary object version of a primitive is created make it possible to define methods on primitives. When you do:

console.log("example".toUpperCase()); 

in specification terms, a String object is created (by the GetValue operation) and then the property toUpperCase is looked up on that object and (in the above) called. Primitive strings therefore get their toUpperCase (and other standard methods) from String.prototype and Object.prototype . But the temporary object that gets created is not accessible to code except in some edge cases,¹ and JavaScript engines can avoid literally creating the object outside of those edge cases. The advantage to that is that new methods can be added to String.prototype and used on primitive strings.

¹ «What edge cases?» I hear you ask. The most common one I can think of is when you’ve added your own method to String.prototype (or similar) in loose mode code:

Object.defineProperty(String.prototype, "example", < value() < console.log(`typeof this: $`); console.log(`this instance of String: $`); >, writable: true, configurable: true >);"foo".example(); // typeof this: object // this instance of String: true

There, the JavaScript engine was forced to create the String object because this can’t be a primitive in loose mode.

Strict mode makes it possible to avoid creating the object, because in strict mode this isn’t required to be an object type, it can be a primitive (in this case, a primitive string):

"use strict"; Object.defineProperty(String.prototype, "example", < value() < console.log(`typeof this: $`); console.log(`this instance of String: $`); >, writable: true, configurable: true >);"foo".example(); // typeof this: string // this instanceof String: false

Why primitive datatypes are not allowed in, This isn’t really an answer to why «Java can’t use primitive types in an ArrayList because it can only use classes in an ArrayList» doesn’t address why it can’t use primitive types. Particularly when the question is worded to show the question asker understands it only accepts reference types. – Andrew.

What is the difference between string primitives and String objects in JavaScript?

JavaScript has two main type categories, primitives and objects.

var s = 'test'; var ss = new String('test'); 

The single quote/double quote patterns are identical in terms of functionality. That aside, the behaviour you are trying to name is called auto-boxing. So what actually happens is that a primitive is converted to its wrapper type when a method of the wrapper type is invoked. Put simple:

Is a primitive data type. It has no methods, it is nothing more than a pointer to a raw data memory reference, which explains the much faster random access speed.

So what happens when you do s.charAt(i) for instance?

Since s is not an instance of String , JavaScript will auto-box s , which has typeof string to its wrapper type, String , with typeof object or more precisely s.valueOf(s).prototype.toString.call = [object String] .

The auto-boxing behaviour casts s back and forth to its wrapper type as needed, but the standard operations are incredibly fast since you are dealing with a simpler data type. However auto-boxing and Object.prototype.valueOf have different effects.

If you want to force the auto-boxing or to cast a primitive to its wrapper type, you can use Object.prototype.valueOf , but the behaviour is different. Based on a wide variety of test scenarios auto-boxing only applies the ‘required’ methods, without altering the primitive nature of the variable. Which is why you get better speed.

This is rather implementation-dependent, but I’ll take a shot. I’ll exemplify with V8 but I assume other engines use similar approaches.

A string primitive is parsed to a v8::String object. Hence, methods can be invoked directly on it as mentioned by jfriend00 .

A String object, in the other hand, is parsed to a v8::StringObject which extends Object and, apart from being a full fledged object, serves as a wrapper for v8::String .

Now it is only logical, a call to new String(»).method() has to unbox this v8::StringObject ‘s v8::String before executing the method, hence it is slower.

In many other languages, primitive values do not have methods.

The way MDN puts it seems to be the simplest way to explain how primitives’ auto-boxing works (as also mentioned in flav ‘s answer), that is, how JavaScript’s primitive-y values can invoke methods.

However, a smart engine will not convert a string primitive-y to String object every time you need to call a method. This is also informatively mentioned in the Annotated ES5 spec. with regard to resolving properties (and «methods»¹) of primitive values:

NOTE The object that may be created in step 1 is not accessible outside of the above method. An implementation might choose to avoid the actual creation of the object. [. ]

At very low level, Strings are most often implemented as immutable scalar values. Example wrapper structure:

StringObject > String (> . ) > char[] 

The more far you’re from the primitive, the longer it will take to get to it. In practice, String primitives are much more frequent than StringObject s, hence it is not a surprise for engines to add methods to the String primitives’ corresponding (interpreted) objects’ Class instead of converting back and forth between String and StringObject as MDN’s explanation suggests.

¹ In JavaScript, «method» is just a naming convention for a property which resolves to a value of type function.

In case of string literal we cannot assign properties

var x = "hello" ; x.y = "world"; console.log(x.y); // this will print undefined 

Whereas in case of String Object we can assign properties

var x = new String("hello"); x.y = "world"; console.log(x.y); // this will print world 

Primitive Data Types in Java, Primitive Data Types in Java. Primitive Data types in java can be subdivided into the following four groups: 1. Integer Data Types. Integer Data Types in java stores positive and negative. Data types like byte, short, int, and long fall under this category of data types. Byte: Byte data type in java can store numbers falling …

How is primitive type int actually converted to a String?

This is called string conversion . The JLS, Section 5.1.11, states:

Any type may be converted to type String by string conversion .

A value x of primitive type T is first converted to a reference value as if by giving it as an argument to an appropriate class instance creation expression (§15.9):

This reference value is then converted to type String by string conversion.

Now only reference values need to be considered:

  • If the reference is null , it is converted to the string «null» (four ASCII characters n , u , l , l ).
  • Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null , then the string «null» is used instead.

So, the int is converted to an Integer , not by boxing conversion, but by new Integer(x) , then toString() is called on it.

It’s technically not a boxing conversion; string conversion has been in the language since the beginning of Java, where boxing conversions were added in Java 1.5.

In general, an int value is converted to String by calling one of these two methods:

For other primitive values, the corresponding overload of either of these methods are used.

StringBuilder.append()

The expression «» + x is implemented by the compiler as:

new StringBuilder().append("").append(x).toString() 

With x being declared as int , that means that the overload of append() that takes an int parameter will be called.

The source (Java 1.8.0_65) for append(int) is:

@Override public StringBuilder append(int i)
public AbstractStringBuilder append(int i) < if (i == Integer.MIN_VALUE) < append("-2147483648"); return this; >int appendedLength = (i

String.valueOf()

When converting a value to a String without using string concatenation, it is generally done by calling String.valueOf() . For an int value that means valueOf(int) :

public static String valueOf(int i)

The Integer.toString() call is:

public static String toString(int i)

Integer.getChars()

As you can see, both do it by actually calling the package-private method Integer.getChars(int i, int index, char[] buf) .

Neither of them actually creates an instance of Integer , even though the JLS implies it would.

You can use valueOf method for static String for primitive types, such as int, double, float. Some code:

int intValue = 25; String s = String.valueOf(intValue); 

Primitive Data Types in JavaScript, We will discuss all the primitive data types one by one in the below section of the article. 1. Boolean. It is considered as the logical entity which can have either true or false value. 0, -0, null, false, NaN, undefined, or an empty string (“”) are all considered as false value by the boolean object. All other values other than …

Источник

Оцените статью