In Java we usually do:
Class myObject = new Class();
because the new
keyword returns an address.
But why can we do this?:
String myString = "Hello";
as if String
were a primitive?
I asked this to my teacher and he replied that it is because what is in quotes is equivalent to an address, but he is not sure. Can you confirm?
Is "Hello" stored in an instance variable of the class String?
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.
String is an object, in android or java it isn't a primitive type at all. you can use strings to store in SharedPreferences.
Definitely, String is not a primitive data type. It is a derived data type. Derived data types are also called reference types because they refer to an object.
Because a string is an array of characters, it is a composite type.
...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.
The fact that you can use a literal expression doesn't mean that the expression results in a primitive type! That is simply a misconception on your end.
You see:
Integer[] numbers = { 1, 2, 3 };
is also a literal (well, "almost"; as you can only use it for such kind of array init statements); but it is not a primitive type!
And to ask the why part in your question: chances are - simply for convenience. When Java was created, it was meant to be "better" than the C and C++ of those days. And guess what: dealing with strings was pretty annoying and error prone in those languages.
In that sense: introducing string literals could be seen as unique selling point to differentiate Java from its competition!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With