In Java, we can directly use String
to declare a string variable name and specify its value. We do not have to define the string as an array by using new keywor
String is a Java Object and not a primitive data type. String is part of the java.lang package that is imported by default in any java project.
There is no need to define an array of char, just use String.
Possible duplicate: Java String import
I think you are confusing 'primitive' and 'literal'. A primitive is a datatype that is not an object. A literal is a convenient way of describing the bit pattern for a datatype. For instance -1 describes the bit pattern 0xFFFFFFFF for an int,and 'a' describes the unicode code point for a lower case A in 16 bits (0x0061). Literals aren't restricted to describing primitive datatypes. You can describe an array. For instance, int[] a = {1, 2, 3};
.
A string literal is just a way of describing an immutable array of characters with some methods attached. The literal is syntactic sugar for describing something that would otherwise be very complicated. For example:
String s = "ab";
Is much simpler than:
char[] c = new char[2];
c[0] = 'a';
c[1] = 'b';
String s = new String(c);
The String Javadoc clearly indicates that String
is a subclass of Object
; and further String.equals(Object) overrides Object.equals(Object).
JLS-3.10.5. String Literals specifies that
A string literal consists of zero or more characters enclosed in double quotes.
Also, JLS-4.3.3. The Class String adds
Instances of class String represent sequences of Unicode code points.
A String object has a constant (unchanging) value.
String literals (§3.10.5) are references to instances of class String.
The string concatenation operator + (§15.18.1) implicitly creates a new String object when the result is not a compile-time constant expression (§15.28).
It's also worth pointing out that arrays are also Object
(s), and An Array of Characters is Not a String. Finally, if a String
wasn't an Object
it couldn't be null
.
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.
Also class has made it possible to make strings immutable and final to enhance security and efficiency by allowing pooling.
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.
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.