Java value Reference and object reference difference Demo

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/gundsoul/article/details/4927404

Previously, Java objects were known to be sub-object references and value references, and there were 8 underlying data types known as reference data types, such as Int,short,long,byte,float,double,char,boolean, and others as object references. But the other object reference I always thought with C inside is the same pointer pass, until today only found that the original Java there is no world.

1. Method invocation is not a pointer passing like C, but a reference to the copy

such as code:

    1.     void func1 (list s)   {
    2.         s.add (
    3.     }
    4.     void test ()  {
    5.          list<string> list = new  ArrayList<String> ();
    6.         list.add (
    7. &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;FUNC1 (list);
    8.         system.out.println (List.size ());  //  here the result is 2 
    9. &NBSP;&NBSP;&NBSP;&NBSP;}

Used to think that the func1 inside the s with the outside list variable is the same reference (for a moment to understand as the pointer good) that is in the stack (stack) is the same thing, this conclusion is understandable, but look at the code:

    1. void func (String s) {
    2. s + = "tail";
    3. }
    4. void Test () {
    5. String a = "abc";
    6. Func (a);
    7. System.out.println (a); //The result here is ABC
    8. }

After discussion, it turns out that s in a and func inside a stack are completely different two references, although they point to the object in the same heap (heap), it's not the same as the result of the code above, just because string is a non-mutable class (immutable). Simply put, an instance is not modifiable. Execute s + = "tail" in Func, and when the operation, s this reference has become to point to the heap inside another value is "Abctail" the object, the old s reference has been discarded, can be collected at any time by GC

2. The position of the string object in memory

Since string is a immutable class, we can not create a string instance of the same value without repeating it, so we have the concept of string pool in the JVM. Simply put, the string pool contains a reference to the string object inside the heap. Look at the code:

    1. String s = "abc";

When the program executes the code, the JVM finds a String object reference in the string pool through the equal ("ABC") method, and if not, creates a string object in the heap and saves the object's reference to string Pool, and if so, return a reference to the object directly.

Let's look at a very similar code:

    1. string s = new string ("abc");

When the program executes the code, the JVM generates the string object like a normal object, saves it in the heap, returns the reference directly, and does not interact with the string pool, so the benefits of string pool are not being played. Aren't we going to use the new method to create a string? The answer is that the JVM also provides a method: String.intern (); Let string pool manage this string object.

The Intern method works by first creating an identical string object in the heap, placing a reference to the object in the string pool, and finally returning it to the caller, looking at the code:

    1.         string s1= new string ( "abc"); 
    2.         string s2=s1.intern ();  
    3.         string s3= "abc";
    4.         system.out.println (S1==S2);  //false
    5.         system.out.println (S2==S3);  // True
    6.         system.out.println (S1==S3);  //false
    • S1 refers to a normal string object in the heap that does not have a reference to the object in the string pool.
    • S2 is a reference to another string object in the heap, and the reference to the object already exists in the string pool.
    • S3 at the time of creation, the JVM finds that there is already a similar object by looking up the string pool, so it returns a reference to the S3 object directly.

Conclusion: We should try to avoid using string s = new String ("abc") When writing Java code, because the resulting object is not "registered" in the string pool and cannot be reused if such an object already exists. We can re-create the object by using S = S.intern (), and "register" it in the string pool to facilitate subsequent reuse.

3. In-depth JVM memory partitioning

Because the JVM has its own special rules on the use of heap and stack memory, in-depth understanding of how the JVM uses memory, it helps us to understand exactly where our objects are when we write our programs, which helps us to optimize our code in multithreaded programs and high performance-demanding programs. Interested students can refer to Sun's Official document (http://java.sun.com/docs/books/jvms/second_edition/html/Overview.doc.html#1732), The following is a brief description of some of the knowledge.

A. Each thread has its own exclusive stack, which holds the method and its local variables that are executed by the current thread

B. A portion of the heap is a public area, storing an array of class instances (classes instance) and allocated memory (array)

C. The heap has its own separate memory area for each thread, which holds the following:

Run a constant-time pool (runtime constant pool), which is part of the string pool mentioned above

Method code, which is the method code that the thread executes

The static variables and methods (static variables and method), variables and methods of the static type that we define are stored here

For a more detailed description, refer to the picture:

Java value Reference and object reference difference Demo

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.