[Java Study Notes] story drawn from string STR = "ABC"

Source: Internet
Author: User

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

The topic is derived from the following:

  1. Public class stringtest {
  2. Public static void main (string [] ARGs ){
  3. String str1 = new string ("ABC ");
  4. String str2 = "ABC ";
  5. If (str1 = str2 ){
  6. System. Out. println ("str1 = str2 ");
  7. } Else {
  8. System. Out. println ("str1! = Str2 ");
  9. }
  10. String str3 = "ABC ";
  11. If (str2 = str3 ){
  12. System. Out. println ("str2 = str3 ");
  13. } Else {
  14. System. Out. println ("str2! = Str3 ");
  15. }
  16. Str1 = str1.intern ();
  17. If (str1 = str2 ){
  18. System. Out. println ("str1 = str2 ");
  19. } Else {
  20. System. Out. println ("str1! = Str2 ");
  21. }
  22. String str4 = new string ("ABC ");
  23. Str4 = str4.intern ();
  24. If (str1 = str4 ){
  25. System. Out. println ("str1 = str4 ");
  26. } Else {
  27. System. Out. println ("str1! = Str4 ");
  28. }
  29. }
  30. }

What is the output of this program?

Answer:

  1. Str1! = Str2
  2. Str2 = str3
  3. Str1 = str2
  4. Str1 = str4

First, let's take a look at how to generate a string-type object:

String has a so-called String constant pool, which is a special space (note that this is on permgen, which is used by JVM to save class definitions andConstant poolThe reserved space. The default value is 64 MB. String STR = "ABC" is to first define a variable named 'str' to reference the string class object: String STR; then use the equals method (the string class overwrites the equals method) determine whether the Special Space (String constant pool) has ABC.The reference pointing to ABC in the stack is assigned to Str.Otherwise, open an address for storing the nominal value "ABC" in this special space (String constant pool ).HeapCreate a new string class Object o, point O's string value to this address, and write down the referenced object o next to this address in the stack. Finally, point STR to the o address of the object.

STR (stack)-> O (stack)-> ABC (Stack -- constant pool)

 

String str2 = new string ("ABC"), where "ABC" itself is an object in the pool, and when new string () is executed at runtime, copy the objects in the pool to heap, and assign the reference of this object in heap to S.This statement creates two string objects.. It references the ABC object created on the stack. So STR and str2 point to different objects, which are different. In this case, we can understand the 3-15 lines of the program.

 

String has an intern () method. This method is a local method. Calling it triggers a search process. ABC must exist (ABC exists here ), it tells JVM that an ABC object already exists and returns a reference to it. Therefore, the printed results at 16--27 are equal.

The intern method makes string creation more space-saving and faster with =. Note: in Java, intern is often automatically used. Let's look at the example below.

Package org. BUPT. test;
Public class stringinternexample {
Private Static char [] chars =
{'A', 's', 't', 'R', 'I', 'n', 'G '};
Public static void main (string [] ARGs ){
// (0). We use this statement to define a string.
String astring = "astring ";
// (1) for the first example, we connect two strings, which are known during compilation.
String aconcatentatedstring = "A" + "string ";
Printresults ("(1 )",
"Astring", astring,
"Aconcatentatedstring", aconcatentatedstring); // true, true
// (2) for the second example, the same string is created, but its content is not known until runtime.
String aruntimestring = new string (chars );
Printresults ("(2 )",
"Astring", astring,
"Aruntimestring", aruntimestring); // false, true
// (3) for the third example, create a string and call Intern
String aninternedstring = aruntimestring. Intern ();
Printresults ("(3 )",
"Astring", astring,
"Aninternedstring", aninternedstring); // true, true
// (4) for the fourth example, we explicitly give its value.
String anexplicitstring = new string ("astring ");
Printresults ("(4 )",
"Astring", astring,
"Anexplicitstring", anexplicitstring); // false, true
// (5) for the fifth example, let's take a look at the test of the input parameter.
If (ARGs. length> 0 ){
String firstarg = ARGs [0];
Printresults ("(5 )",
"Astring", astring,
"Firstarg", firstarg); // false, false
// (6) Test the intern of input parameters
String firstarginterned = firstarg. Intern ();
Printresults ("(6 )",
"Astring", astring,
"Firstarginterned", firstarginterned); // false, false
}
}
/**
* Print equals (...) and =
*/
Private Static void printresults (string tag, string s1name, string S1, string s2name, string S2 ){
System. Out. println (TAG );
System. Out. println ("" + s1name + "=" + s2name + ":" + (S1 = S2 ));
System. Out. println ("" + s1name + ". Equals (" + s2name + "):" + s1.equals (S2 ));
System. Out. println ();
}
}
The result is as follows:

(1)
Astring = aconcatentatedstring: True
Astring. Equals (aconcatentatedstring): True
(2)
Astring = aruntimestring: false
Astring. Equals (aruntimestring): True
(3)
Astring = aninternedstring: True
Astring. Equals (aninternedstring): True
(4)
Astring = anexplicitstring: false
Astring. Equals (anexplicitstring): True
(5)
Astring = firstarg: false
Astring. Equals (firstarg): True
(6)
Astring = firstarginterned: True
Astring. Equals (firstarginterned): True
We can analyze them one by one:

Scenario (1): use the "+" connection word to connect two strings known during compilation. The result is true for = and equals, note + the action will be executed during compilation.

Scenario (2): A New String (chars) is used to create a string that is only known during running. The result is = false, and equals is true, this string is created only during running.

Case (3): Use the intern method to create a string. The result = and equals are both true. The intern analysis on the front side shows that intern only returns the same reference.

Case (4): An intern method is used to create a string. The result is = false and equals is true, indicating that a new object is created.

Case (5): it is essentially the same as case (2.

Case (6): it is essentially the same as case (3.

Okay, so we can basically understand the problem of = and equals.

Finally, the equals () method is used to compare whether the values in the packaging class are equal. When testing whether the references of the two packaging classes point to the same object, = is used, because = is used to determine whether the two basic data types are the same.

 

Here is a brief summary of a netizen's blog:

Java Virtual Machine maintains an internal list of references for interned strings (pool of unique strings) to avoid duplicate string objects in heap memory. whenever the JVM loads string literal from class file and executes, it checks whether that string exists in the internal list or not. if it already exists in the list, then it does not create a new string and it uses reference to the existing String object. JVM does this type of checking internally for string literal but not for String object which it creates through 'new' keyword. you can explicitly force JVM to do this type of checking for string objects which are created through 'new' keyword using string. intern () method. this forces JVM to check the internal list and use the existing String object if it is already present.

So the conclusion is, JVM maintains unique string objects for string literals internally. programmers need not bother about string literals but they shoshould bother about string objects that are created using 'new' keyword and they shoshould use intern () method to avoid duplicate string objects in heap memory which in turn improves Java performance. see the following section for more information.

 

Some of these details cannot be verified for the moment. Please take a critical look at this article.

 

Finally, let's judge these problems:

1. "A" = ""
2. "A" + "B" = "AB"
3. "A". tolowercase () = ""
4. "A" + "B". tolowercase () = "AB"

5. "A". tolowercase () = ""

 

 

The preceding statements are output in sysout. Which statements are true and false?

1. True, for the above reasons.

2. True: two identified string constants. After the compiler is optimized, they are already "AB" in the class, and the value of their string constants is determined during compilation.

3. True. If the value does not change, the object reference of the original string is returned.

4. false: After the string is lowercase, an object is referenced and then added to the string. The referenced + operation cannot determine the result during compilation, that is, "a" + "B ". tolowercase () cannot be optimized by the compiler. During the program running, it is dynamically allocated and the object is referenced and returned. So "AB" is in the String constant pool, "a" + "B ". tolowercase () on the stack, the "=" operator compares the memory address, so the comparison result is false.

5. False: A New String object is referenced and returned.

 

Let's just talk about the stack and stack.

Heap dynamically allocates the memory size and does not need to tell the compiler in advance for the lifetime. Automatic garbage collection is responsible for garbage collection. However, because the memory is dynamically allocated during runtime, the access speed is slow. Space allocation on the heap is established through commands such as new, and class instantiation objects are allocated from the heap.

The stack mainly stores some basic types of variables (INT, short, long, byte, float, double, Boolean, and char) and object handles, and the access speed is faster than the heap. Pay attention to the packaging class data, such as integer, String, double, and so on. These are not on the stack.

In addition, stack data can be shared.

For example:

Int A = 5;

Int B = 5;

It works in this way.

When JVM processes int A = 5, it first creates a reference with the variable A on the stack, and then finds whether there is another 5 value on the stack. If not, store 5 and point A to 5. Then, process int B = 5. After the reference of B is created, B is directed to 5 because the value 5 already exists in the stack.

As a result, a and B point to the memory address of 5 at the same time.

In the afternoon, I chatted with an online friend about these things. He gave me a suggestion to read related JVM books and introduced the methods in javap.

 

Author: gnuhpc
Source: http://www.cnblogs.com/gnuhpc/

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.