6

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?

3 Answers3

11

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.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • +1 Great, where did you find this info. I should delete my answer as I was wrong that no constructor is called. – Juned Ahsan Jul 15 '13 at 10:31
  • One would think that the JVM can use a more efficient private constructor that does not have to make a copy of the array, though. – Thilo Jul 15 '13 at 10:37
  • This is like String.intern() done by JVM automatically – Evgeniy Dorofeev Jul 15 '13 at 10:41
  • if it internally defaults to using new String("str") then how it differentiates whether to not put it in heap memory in this case – Sudhanshu Gupta Jul 15 '13 at 10:43
  • @Sudhanshu Kumar take a look at String.intern javadoc, there's some explanation – Evgeniy Dorofeev Jul 15 '13 at 10:45
  • @SudhanshuKumar In Java 7+, all Strings are on the heap. – Peter Lawrey Jul 15 '13 at 11:03
  • @EvgeniyDorofeev I don't understand why do you think that `String(char value[])` is called. Strings are on the heap is one thing, but why do you say it affects which constructor is used? – yair Jul 15 '13 at 11:33
  • [javadoc says it's equivalent](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html), but how do we know that this constructor is actually used? – yair Jul 15 '13 at 11:38
  • @yair String has 7 constructors out of them only String(char[]) and String(char[],int,int) can create a String from char array. – Evgeniy Dorofeev Jul 15 '13 at 11:51
  • Do you have a reference for this? Perhaps from OpenJDK source? – selig Jul 15 '13 at 12:01
  • @yair The main point is that String str = "hello" uses no constructor at all but is assigned a reference to a String from pool. But that String from pool is created by JVM using one of String constructors. To know for sure exactly which one it needs to take a look at JVM source – Evgeniy Dorofeev Jul 15 '13 at 12:12
  • 1
    @EvgeniyDorofeev yes I understand that. So your answer apparently should state that (1) the `String` instance is actually not created during execution of the line `String str = "hello";`. (2) the exact constructor that is used in the first place is JVM implementation dependent. – yair Jul 15 '13 at 13:27
3

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;
}
Community
  • 1
  • 1
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • How can we infer that this constructor is called? It is public and inefficient (has to make a copy of the array). One would think that the JVM can use a more efficient private constructor. – Thilo Jul 15 '13 at 10:38
  • @Thilo Good observation , but I haven't seen any `private` constructor in `String` and this constructor comes closer to what the doc says. – AllTooSir Jul 15 '13 at 10:40
  • 1
    There is one at Line 645 in http://hg.openjdk.java.net/jdk7/build-gate/jdk/file/tip/src/share/classes/java/lang/String.java – Thilo Jul 15 '13 at 10:42
  • @Thilo checked the source now , got that. – AllTooSir Jul 15 '13 at 10:48
1

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

How can a string be initialized using " "?

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Can you tell us how "Hello" will be interned in the String pool ? Will no constructor will be called at all ? – AllTooSir Jul 15 '13 at 10:23
  • 2
    This is more of a discussion of how to initialize string variables than how a string literal is converted to a string instance at runtime, which as I think, is the intention of this question. – SpaceTrucker Jul 15 '13 at 11:02