Comparison from Java stack to Equals and =

Source: Internet
Author: User

Comparison from Java stack to Equals and =

Java heap and stack

 

Both stacks and stacks are places where Java is used to store data in Ram. Unlike C ++, Java automatically manages stacks and stacks, and programmers cannot directly set stacks or stacks.
The Java heap is a runtime data zone, from which the class objects allocate space. These objects are created using commands such as new, newarray, anewarray, and multianewarray. They do not need program code to be explicitly released. The heap is responsible for garbage collection. The advantage of the heap is that the memory size can be dynamically allocated, and the lifetime does not have to be told in advance because the heap dynamically allocates memory at runtime, the Java Garbage Collector automatically collects the unused data. However, the slow access speed is due to the need to dynamically allocate memory during runtime.


The advantage of stack is that the access speed is faster than that of stack, second only to register, and stack data can be shared. However, the disadvantage is that the data size and lifetime in the stack must be fixed, and there is a lack of flexibility. The stack mainly stores some basic types of variables (, int, short, long, byte, float, double, boolean, char) and object handles. A very important feature of stacks is that data in stacks can be shared.


Suppose we define both:
Int a = 3;
Int B = 3;


The compiler first processes int a = 3. First, it creates a reference with the variable a in the stack, and then finds whether the value 3 in the stack exists. If no value is found, store 3 and point a to 3. Then process int B = 3. After the referenced variable of B is created, B is directed to 3 because there is already 3 in the stack. In this way, both a and B point to 3 at the same time. At this time, if a is set to 4 again, the compiler will re-search whether there are 4 values in the stack. If not, it will store 4 and make a point to 4; if yes, direct a to this address. Therefore, changing the value of a does not affect the value of B.


Note that the sharing of data is different from the sharing of two objects pointing to one object at the same time, because the modification of a does not affect B, which is completed by the compiler, it facilitates space saving. A variable referenced by an object modifies the internal state of the object, which affects the variable referenced by another object.
String is a special packaging data.


Available:
String str = new String ("abc ");
String str = "abc ";


The first method is to use new () to create an object, which is stored in the heap. Each call creates a new object. The second is to first create a String class object in the stack to reference the variable str, and then find whether the stack contains "abc". If not, store "abc" in the stack and send str to "abc". If "abc" already exists, direct str to "abc ".


Use the equals () method to compare the values in a class. Use the = method to test whether the references of the two classes point to the same object. The example below illustrates the above theory.
String str1 = "abc ";
String str2 = "abc ";
System. out. println (str1 = str2); // true
It can be seen that str1 and str2 point to the same object.


String str1 = new String ("abc ");
String str2 = new String ("abc ");
System. out. println (str1 = str2); // false
The new method is used to generate different objects. Each time one is generated.
Therefore, the second method (String str1 = "abc") is used to create multiple "abc" strings. Only one object exists in the memory. this method is advantageous and saves memory space. at the same time, it can improve the program running speed to a certain extent, because the JVM will automatically decide whether to create a new object based on the actual situation of the data in the stack. For the code of String str = new String ("abc"), a new object is created in the heap, regardless of whether the String value is equal, whether it is necessary to create a new object, this increases the burden on the program.
On the other hand, NOTE: When we define classes using formats such as String str = "abc";, we always take it for granted that the str object of the String class is created. Worry trap! The object may not be created! Instead, it may only point to a previously created object. Only by using the new () method can a new object be created every time.
Because of the immutable property of the String class, when the String variable needs to change its value frequently, you should consider using the StringBuffer class to improve program efficiency.

 

**************************************** **************************************** **************************************** ************************************

 

Differences between Equals and = in Java

Java data types can be divided into two types:
1. The basic data type, also known as the original data type. Byte, short, char, int, long, float, double, boolean
The comparison between them applies the double equal sign (=) to compare their values.
2. Composite data type (class)
When they use (=) for comparison, they compare their storage addresses in the memory, so unless they are the same new object, their comparison result is true, otherwise the comparison result is false. All classes in JAVA are inherited from the base class Object. An equals method is defined in the base class of the Object. The initial behavior of this method is to compare the memory address of the Object, however, in some class libraries, this method is overwritten, such as String, Integer, and Date. Among these classes, equals has its own implementation, instead of the storage address of the comparison class in the heap memory.
For equals comparison between composite data types, if the equals method is not overwritten, the comparison between them is based on the address value of their storage location in the memory, because the equals method of the Object is compared with the binary equal sign (=), the comparison result is the same as that of the binary equal sign (=.

 

public class TestString {public static void main(String[] args) {String s1 = "Monday";String s2 = "Monday";if (s1 == s2) {System.out.println("s1 == s2");} else {System.out.println("s1 != s2");}}}

 

 

Compile and run the program. Output: s1 = s2 Description: s1 and s2 reference the same String object -- "Monday "!
2. If you change the program a little bit, you may find it strange:

 

public class TestString {public static void main(String[] args) {String s1 = "Monday";String s2 = new String("Monday");if (s1 == s2){System.out.println("s1 == s2");}else{System.out.println("s1 != s2");}if (s1.equals(s2)) {System.out.println("s1 equals s2");}else{System.out.println("s1 not equals s2");}}}

We will create s2 with the new operator
Program output:
S1! = S2
S1 equals s2
Note: s1 s2 references two "Monday" String objects respectively.


3. String Buffer Pool
It turns out that the program will create a string buffer pool when running. When expression s2 = "Monday" is used to create a string, the program first searches for objects with the same value in the String buffer pool. In the first program, s1 is first placed in the pool. Therefore, when s2 is created, the program finds s1 with the same value
Reference s2 to the object referenced by s1 "Monday"
In the second stage, the new operator is used, and he clearly tells the program: "I want a new one! Don't be old! "So a new" Monday "Sting object is created in the memory. They have the same value but different locations. One is swimming in the pool and the other is resting on the shore. Oh, it's a waste of resources. What should we do separately?


4. Change the program again:

 

 

public class TestString {public static void main(String[] args) {String s1 = "Monday";String s2 = new String("Monday");s2 = s2.intern();if (s1 == s2){System.out.println("s1 == s2");}else{System.out.println("s1 != s2");}if (s1.equals(s2)) {System.out.println("s1 equals s2");}else{System.out.println("s1 not equals s2");}}}

Join this time: s2 = s2.intern ();
Program output:
S1 = s2
S1 equals s2
Originally, (the return value of the java. lang. String intern () method "abc". intern () method is still the String "abc". It seems that this method is useless. But in fact, it performs a small action: Check whether there is a string such as "abc" in the string pool. If yes, the string in the pool is returned; if not, this method adds "abc" to the string pool and then returns its reference.
)

 

 

**************************************** **************************************** **************************************** ************************************

 

View the source code summary:

 

public boolean equals(Object anObject) {        if (this == anObject) {            return true;        }        if (anObject instanceof String) {            String anotherString = (String) anObject;            int n = value.length;            if (n == anotherString.value.length) {                char v1[] = value;                char v2[] = anotherString.value;                int i = 0;                while (n-- != 0) {                    if (v1[i] != v2[i])                            return false;                    i++;                }                return true;            }        }        return false;    }

 

 

The above section is the source code of String equals. Through careful interpretation, we can find the mysteries.

The equals method of String rewriting retains the Object to compare whether the content addresses of the two objects are equal. On this basis, a comparison String value is added to determine whether it is equal. What does this mean. If the object in the equals brackets is not of the String type, compare whether it is equal to the memory address of the original object. If instanceofString, convert the object to String first, and then change its value to a char array, that is, the following value, if their char array is of the same length, traverse the char array one by one to see if it is the same. If both are the same, equals is true; otherwise, it is false.
 


 

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.