Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which String class constructor get called when String object created by using String literal [duplicate]

Tags:

java

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?

like image 334
Sudhanshu Gupta Avatar asked Jul 15 '13 10:07

Sudhanshu Gupta


2 Answers

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.

like image 161
Evgeniy Dorofeev Avatar answered Oct 07 '22 11:10

Evgeniy Dorofeev


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.

  1. 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.

  2. 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;
}
like image 3
AllTooSir Avatar answered Oct 07 '22 13:10

AllTooSir