3

How does the String class work? I have gone through many posts and I have not found an answer.

String str="ABC";

Does the above statement call the constructor?

public String(char[] paramArrayOfChar)

if yes ,how does it call it? We are using the assignment operator. How does it call the String class constructor.

Willi Mentzel
  • 27,862
  • 20
  • 113
  • 121
alakhya
  • 35
  • 1
  • 7
  • 1
    The answer you are looking for can be found here http://stackoverflow.com/questions/7088928/java-strings-how-do-they-work – Twahanz Jun 12 '16 at 10:13
  • A possible cause of confusion, perhaps for those who have previously studied C and/or C++, is that the literal "ABC" is *not* a char array. It already is a String, and exists as a String object in its own right before the method in which it appears is even called. Therefore there is no need to call any constructor. The statement `String str = "ABC"` simply assigns a *reference*. – Klitos Kyriacou Jun 12 '16 at 11:14
  • @KlitosKyriacou, I think, a string literal **is** a `const char[]` array in C languages – Andrew Tobilko Jun 12 '16 at 11:19
  • @AndrewTobilko you're right, I worded it wrongly: I mean those who've studied C and/or C++ know "ABC" as a const char[] literal, but it is not that in Java. In Java this literal is a String object right from the start. – Klitos Kyriacou Jun 12 '16 at 11:27
  • @KlitosKyriacou, "Java automatically constructs a String object" by using a char array as a base – Andrew Tobilko Jun 12 '16 at 12:31
  • @AndrewTobilko "A string literal is a reference to an instance of class String" (Java Language Specification, 8th ed.) The JLS doesn't specify that a String contains a char array as a base (nor does the API doc) as that is an implementation detail. – Klitos Kyriacou Jun 12 '16 at 13:16
  • Simply saying that, A string object is immutable which stores the string literal as reference in JVM heap. – S.K. Venkat Jun 13 '16 at 05:02

5 Answers5

1

It's a little more complicated than that. Strings are stored in a global store in Java, so the constructor might be called once, the JVM decides which strings to "intern" (put into global store) and if you declare "ABC" another time, it might be the same instance.

Silverclaw
  • 1,316
  • 2
  • 15
  • 28
1

Does the above statement call the constructor?

No, it doesn't. It looks like String str = new String("ABC") if the String Pool doesn't contain "ABC". When you write "ABC" again, it will use the old version from the internal storage. If the Pool already contains this value - there is no object that is created, just pulls out this value from the storage (that is true when we are talking about using String literals like "ABC", but when we are using the new keyword, the behavior is a slightly different).

"ABC" is already defined object, which internally contains the value as char[] {'A','B','C'}. I may assume that somewhere the "ABC" instance is created as new String(new char[]{'A','B','C'}) (the specification says nothing about that).

Community
  • 1
  • 1
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
  • If the String Pool does not contain the "ABC".will it call String constructor.if yes,i want to understand how it is calling the constructor. – alakhya Jun 12 '16 at 10:38
  • @alakhya, the constructor is not called, the `"ABC"` value returns from the String pool – Andrew Tobilko Jun 12 '16 at 10:53
1

edit when we want to use it like this String str1 = "Hello World"; we are using String Interning ( by the way its use it by many programming lanuage ) :

In computer science, string interning is a method of storing only one copy of each distinct string value, which must be immutable. Interning strings makes some string processing tasks more time- or space-efficient at the cost of requiring more time when the string is created or interned. The distinct values are stored in a string intern pool.

JVM checks the String constant pool first and if the string does not exist, it creates a new String object, how ? When the intern() method is invoked on a String object it looks the string contained by this String object in the pool, if the string is found there then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

example :

// s1 == s2 is false
String s1 = new String("sometext");
// s1 == s2 is true
//String s1 = new String("sometext").intern();
String s2 = s1.intern();
String s3 = "sometext";
System.out.println(s2 == s3);

another example (read abbas value and change it)

        String str = "abbas";
        Field value = str.getClass().getDeclaredField("value");
        value.setAccessible(true);
        char[] Value = (char[]) value.get(str);
        System.out.println("Value = " + Arrays.toString(Value));

        char[] newVal = new char[]{'f','t','b','h','p'};
        value.set(str,newVal);
        Value = (char[]) value.get(str);
        System.out.println("Value = " + Arrays.toString(Value));
        //Value = [a, b, b, a, s]
        //Value = [f, t, b, h, p]
Hosseini
  • 547
  • 3
  • 15
1

Because strings are a common and important part of programming, Java has added special support for several string operations within the syntax of the language. These operations include the automatic creation of new String instances from string literals, concatenation of multiple String objects by use of the + operator, and the conversion of other data types to a string representation. There are explicit methods available to perform all of these functions, but Java does them automatically as a convenience for the programmer and to add clarity

String Literals

The earlier examples showed how to explicitly create a String instance from an array of characters by using the new operator. However, there is an easier way to do this using a string literal. For each string literal in your program, Java automatically constructs a String object. Thus, you can use a string literal to initialize a String object. For example, the following code fragment creates two equivalent strings:

char chars[] = { 'a', 'b', 'c' };
String s1 = new String(chars);
String s2 = "abc"; // use string literal

Because a String object is created for every string literal, you can use a string literal any place you can use a String object. For example, you can call methods directly on a quoted string as if it were an object reference, as the following statement shows. It calls the length( ) method on the string “abc”. As expected, it prints “3”. System.out.println("abc".length());

user3519807
  • 133
  • 1
  • 9
-1

In the section of string literals, the Java Language Specification does not specify how strings are created. It only specifies that they are interned using String.intern().

Therefore, there is no guarantee as to how an implementation might create strings.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121