JavaRush /Java Blog /Random EN /Translation: Creating String objects in Java - using " " ...
FellowSparrow
Level 12
Lvov

Translation: Creating String objects in Java - using " " or constructor?

Published in the Random EN group
Original: Create Java String Using “ ” or Constructor? By X Wang Translation: Creating String Objects in Java - UsageIn Java, a string can be created using two methods:
String x = "abc";
String y = new String("abc");
What is the difference between using double quotes and using a constructor?

1. Double Quotes vs. Constructor

This question can be answered by looking at two simple examples. Example 1:
String a = "abcd";
String b = "abcd";
System.out.println(a == b);  // True
System.out.println(a.equals(b)); // True
a==btrue because they aboth brefer to the same object - a string declared as a literal (string literal below) in the method area (we refer the reader to the source on our resource: Top 8 diagrams for understanding Java , diagram 8). When the same string literal is created more than once, only one copy of the string is stored in memory, just one instance of it (in our case "abcd"). This is called "string interning". All string constants processed at compile time are automatically interned in Java. Example 2:
String c = new String("abcd");
String d = new String("abcd");
System.out.println(c == d);  // False
System.out.println(c.equals(d)); // True
c==dfalse because cthey drefer to two different objects in memory (on the heap). Different objects always have different references. This diagram illustrates the two situations described above: Translation: Creating String Objects in Java - Usage

2. Interning strings at program execution stage

The author thanks LukasEder (the comment below is his): String interning can also occur during program execution, even if two strings are created using constructors:
String c = new String("abcd").intern();
String d = new String("abcd").intern();
System.out.println(c == d);  // Now true
System.out.println(c.equals(d)); // True

3. When to use double quotes and when to use constructors

Due to the fact that the literal "abcd" is always of type String, using a constructor will create an additional unnecessary object. So double quotes should be used if you just need to create a string. If you actually need to create a new object on the heap, you should use a constructor. Use cases are shown here (original) . (I provide the translated text below. But I still highly recommend that you familiarize yourself with the commentators’ code at this link.)

The substring() method in JDK 6 and JDK 7

The substring() Method in JDK 6 and JDK 7 By X Wang The method substring(int beginIndex, int endIndex)in JDK 6 and JDK 7 is different. Knowing these differences can help you use this method better. For the sake of ease of reading, below substring()we will mean the full syntax, i.e. substring(int beginIndex, int endIndex).

1. What does substring() do?

The method substring(int beginIndex, int endIndex)returns a string that starts with character number beginIndexand ends with character number endIndex-1.
String x = "abcdef";
x = x.substring(1,3);
System.out.println(x);
Output:
bc

2. What happens when substring() is called?

You may know that, due to immutability x, when assigning x the result of x.substring(1,3), xit points to a completely new row (see diagram): Translation: Creating String Objects in Java - UsageHowever, this diagram is not completely correct; it doesn't demonstrate what's actually going on in the heap. What actually happens when is called substring()is different in JDK 6 and JDK 7.

3. substring() in JDK 6

The string type is supported by array type char. In JDK 6, the class Stringcontains 3 fields: char value[], int offset, int count. They are used to store the actual array of characters, the index of the first character in the array, the number of characters in the line. When the method is called substring(), it creates a new row, but the value of the variable still points to the same array on the heap. The difference between two strings is their number of characters and the index value of the starting character in the array. Translation: Creating String Objects in Java - UsageThe code below is simplified and only contains the basics to demonstrate the problem.
//JDK 6
String(int offset, int count, char value[]) {
	this.value = value;
	this.offset = offset;
	this.count = count;
}

public String substring(int beginIndex, int endIndex) {
	//check boundary
	return  new String(offset + beginIndex, endIndex - beginIndex, value);
}

4. Problem caused by substring() in JDK 6

If you have a VERY long string, but you only need a small part of it, which you get every time using substring(). This will cause execution problems, since you only need a small part, but you still have to store the entire string. For JDK 6, the solution is the code below, which will cast the string to a real substring:
x = x.substring(x, y) + ""
User STepeR formulated a question (see his comment), and it seemed necessary to add point 4. "Problem caused substring()in JDK 6" is a more extensive example. I hope this will be the answer and will help others quickly figure out what the problem is. Here's the code:
String a = "aLongLongString";
String b = a.substring(1, 2);
String c = a.substring(2, 6);
So, in JDK 7 b, objects сof type a Stringcreated by calling a method substring()on an object of type a Stringwill reference two newly created arrays in the heap - Lfor b, ongLfor c. These two new arrays will be stored on the heap ALONG with the original array aLongLongStringreferenced by a. Those. the original array does not disappear anywhere. Now let's return to JDK 6. In JDK 6, a heap contains a single array aLongLongString. After executing the lines of code
String b = a.substring(1, 2);
String c = a.substring(2, 6);
objects brefer cto the same array in the heap, corresponding to the object a: b- to elements from the 1st index to the 2nd, c- to elements from the 2nd index to the 6th (numbering starts from 0, reminder). Those. Obviously, any further access to variables bor c in JDK 6 will actually result in the desired elements of the original array being “counted” into the heap. In JDK 7, any further access to variables bor c will cause an access to the necessary smaller arrays that have already been created and “live” in the heap. Those. Clearly JDK 7 uses physically more memory in situations like this. But let's imagine a possible option: certain substrings of the variable are assigned to the variables b, and in the future everyone uses only them - objects and . Nobody simply accesses the variable a anymore; there are no references to it (this is what the author of the article means). As a result, at some point in time the garbage collector is triggered, and (in the most general form, of course) we get 2 different situations: JDK 6 : the object is destroyed (garbage collected) , BUT - the original huge array in the heap is alive; it is constantly used and . JDK 7: object a is destroyed along with the original array in the heap. This is the point in JDK 6 that can lead to a memory leak. cabcabc

5. substring() in JDK 7

The method has been improved in JDK 7. In JDK 7 substring()it actually creates a new array on the heap. Translation: Creating String Objects in Java - Usage
//JDK 7
public String(char value[], int offset, int count) {
	//check boundary
	this.value = Arrays.copyOfRange(value, offset, offset + count);
}

public String substring(int beginIndex, int endIndex) {
	//check boundary
	int subLen = endIndex - beginIndex;
	return new String(value, beginIndex, subLen);
}
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION