Java heap, stack, stack differences

Source: Internet
Author: User
Tags format definition

Tag: generic stack Stringbu view jdk equals blog record

Java divides memory into two types: one is stack memory, and the other is heap memory .

stack: is an advanced data structure, usually used to hold parameters in a method (function), local variables.
In Java, all base types and reference types are stored in the stack . The data in the stack is typically in the current scopes (that is, by {...} Area).

  Heap: is a dynamically requested memory space (the list that records the free memory space is maintained by the operating system), and the memory space generated by the malloc statement in C is in the heap.
In Java, all objects constructed with new XXX () are stored in the heap , and the object is automatically destroyed when the garbage collector detects that an object is not referenced. So, theoretically, there is no limit to the living space of objects in Java, Whenever a reference type points to it, it can be used anywhere.


Heap-to-stack relationship:

Heap: Heap is heap, which is called dynamic memory, where memory can be reclaimed when it is not needed to allocate to new memory requests, and its in-memory data is unordered, that is, the allocated and subsequently allocated memory does not have any necessary positional relationships, and can be released without sequencing. It is generally freely allocated by the user, and malloc allocates the heap, which needs to be released manually.

Stack: is stack. In fact, there is only one outbound queue, that is, last-in, first-out, and the allocated memory must be released. Generally, by the system automatically allocated, storing the parameters value of the function, local variables, etc., automatically cleared.


Stack's pros and cons:
The advantage is that the stack is accessed faster than the heap, second only to the registers in the CPU. Stack data can be shared

The disadvantage is that the size and lifetime of the data in the stack must be deterministic and inflexible.

The advantages and disadvantages of heap:

The advantage is that the memory size can be allocated dynamically, the lifetime does not have to tell the compiler beforehand, and the Java garbage collector automatically collects the data that is no longer used.

The disadvantage is that the access speed is slower due to the dynamic allocation of memory at run time.

2. There are two kinds of data types in Java.

Base type: int, short, long, byte, float, double, Boolean, char (Note that string is a reference type). If an int a = 3 is stored, it is a literal value.

The origin of the stack: the data of these literals, due to the size of the known, the lifetime is known (these values are fixed in a program block, the program block exits, the field value disappears), for the sake of speed, it exists in the stack.

Reference types include classes, interfaces, arrays, integers, strings, double, and so on. A variable that refers to a type declaration is a reference address that is actually stored in memory by the variable, and the entity is in the heap.
  The wrapper class is a reference type , which is the class (Int→integer) that wraps the corresponding base data type, and auto- boxing and unpacking are conversions between the base type and the reference type .

Why do you want to convert?

Since the base type is converted to a reference type, it is possible to invoke the new object to call the encapsulated method in the wrapper class for a conversion between the basic types or ToString (of course, directly with the class name, to see if the method is static), or if the collection wants to store the base type, The qualified type of a generic can only be the corresponding wrapper type.

3. Comparison of string str =new string ("abc") and string str = "ABC"

String str =new string ("abc")

String str1 = "abc"

System.out.println (str = = str1)

System.out.println (Str.equal (STR1))

Results:

False

True

Cause resolution:

    • The Java runtime Environment has a string pool, which is maintained by the string class.

1. execute the statement string str= "abc"; First, see if there is a string "abc" in the string pool, assign "ABC" directly to STR if it exists, and if it does not exist, create a new string "abc" in the string pool before assigning it to Str.

2. Execute the statement string str = new String ("abc"); Creates a new string "ABC", regardless of whether the string "ABC" exists in the string pool, (note that the new string "ABC" is not in the string pool) and assigns it to Str. This shows that 1. Efficiency is higher than 2 efficiency.

3. String str1= "Java";//point to String Pool
String str2= "blog";//point to String Pool
String s = str1+str2;

The + operator establishes two string objects in the heap, the values of which are "Java", "blog", that is, the two values are copied from the string constant pool, and then two objects are created in the heap.  The object s is then created, and the heap address of "Javablog" is assigned to S. This sentence creates a total of 3 string objects.


System.out.println (s== "Javablog");//The result is false;

The JVM does have an object in the form of a string str= "Javablog", which is placed in a constant pool, but it is at compile-time name. The string s=str1+str2 is known at run time, meaning that STR1+STR2 is created in the heap, so the result is false.
String S= "java" + "blog";//The Javablog object is placed directly into the string pool. System.out.println (s== "Javablog");//The result is true;

String s=str1+ "blog";//Not placed in the string pool, but distributed in the heap. System.out.println (s== "Javablog");//The result is false;

in summary, there are two ways to create a string: Two memory regions (POOL,HEAP)
1. "" Creates a string in the string pool.
2.new When creating a string, first look at whether there is the same string in the pool, if any, copy one copy into the heap, and then return the address in the heap, if none in the pool creates a point in the heap, and then returns the address in the heap.
3. When assigning a value to a string, if the right operand contains one or more string references, then a string object is established in the heap, and a reference such as String s= str1+ "blog" is returned;

The difference between

The 1th type:

String a= "ABC";
String b= "ABC";
System.out.print (A==B);

Result: True

Cause: At compile time, these two "ABC" are considered to be the same object saved to the constant pool, while the runtime JVM considers the two variables to be the same object, so returns True.

---------------------
The 2nd type:

String A=new string ("abc");
String B=new string ("abc");
System.out.print (A==B);

Result: false

Cause: The object created with the constructor is not put into the common sense pool, it is also obvious that this is completely two objects, but the content is the same, of course, the result is false. With Equals () or System.out.print (A.intern () ==b.intern ()), it returns true.

------------------------------
3rd type

String a= "ABC";
String B=new string ("abc");
System.out.print (A==B);

Result: false

Reason: Ibid. In addition, a的类加载时就完成了初始化,而b要在执行引擎执行到那一行代码时才完成初始化。

---------------------------
4th type

String a= "abcdef";
System.out.print (a== "abcdef");

Result: True

Cause: When a string constant appears in a constant pool, the JVM considers the same object to save memory overhead, so the two strings are considered to be the same object.

-------------------------------------------
5th type

String a= "abcdef";
String b= "";
String c=a+b;
System.out.print (c== "abcdef");

Result: false

Cause: At compile time, "ABCEDF" is placed in a constant pool, while the value of C is created in the heap at run time. So it is false.


6. CONCLUSIONS AND recommendations:

(1) When we use a format definition class such as String str = "ABC", we always want to think of course that we created the object str of the String class. Worry about traps! The object may not have been created! The only certainty is that a reference to the string class was created. As to whether the reference is pointing to a new object, it must be considered in terms of context, unless you create a new object with a prominent way through the new () method. Therefore, it is more accurate to say that we have created a reference variable to the object of the String class str, which refers to a variable that points to a string class with the value "ABC". Being aware of this is helpful in troubleshooting bugs that are difficult to find in a program.

(2) The use of string str = "abc", in a way that can improve the speed of the program to a certain extent, because the JVM will automatically based on the actual data in the stack to determine whether it is necessary to create a new object. In the case of string str = new String ("abc"), the code creates a new object in the heap, regardless of whether the string value is equal or not, and it is necessary to create a new object, thereby aggravating the burden of the program. This idea should be the idea of the meta-mode, but it is not known whether the internal JDK implements this pattern.

(3) Use the Equals () method when comparing the values in the wrapper class, and use the = = when testing whether the references to the two wrapper classes point to the same object.

(4) Because of the immutable nature of the string class, you should consider using the StringBuffer class when the string variable needs to change its value frequently to improve program efficiency.

Java heap, stack, stack differences

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.