which constructor of string class get called when we create string object by using String literal .
Example:
String str = "hello";
In this case which constructor of string class get?
which constructor of string class get called when we create string object by using String literal .
Example:
String str = "hello";
In this case which constructor of string class get?
When JVM loads a class containing a String literal
String str = "hello";
it reads string literal from class file in UTF-8 encoding and creates a char array from it
char[] a = {'h', 'e', 'l', 'l', 'o'};
then it creates a String object from this char array using String(char[]) constructor
new String(a)
then JVM places the String object in String pool and assigns the reference to this String object to str
variable.
As per the JVM 5.1 spec
To derive a string literal, the Java Virtual Machine examines the sequence of code points given by the CONSTANT_String_info structure.
If the method String.intern has previously been called on an instance of class String containing a sequence of Unicode code points identical to that given by the CONSTANT_String_info structure, then the result of string literal derivation is a reference to that same instance of class String.
Otherwise, a new instance of class String is created containing the sequence of Unicode code points given by the CONSTANT_String_info structure; a reference to that class instance is the result of string literal derivation. Finally, the intern method of the new String instance is invoked.
Hence from this point we can infer the constructor can be :
String(int[] codePoints, int offset, int count)
Allocates a new String that contains characters from a subarray of the Unicode code point array argument. The offset argument is the index of the first code point of the subarray and the count argument specifies the length of the subarray. The contents of the subarray are converted to chars; subsequent modification of the int array does not affect the newly created string.
Or can even be the private constructor:
// Package private constructor which shares value array for speed.
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
A Java String contains an immutable sequence of Unicode characters. Unlike C/C++, where string is simply an array of char, A Java String is an object of the class java.lang. Java String is, however, special. Unlike an ordinary class:
String is associated with string literal in the form of double-quoted texts such as "Hello, world!". You can assign a string literal directly into a String variable, instead of calling the constructor to create a String instance.
String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object