Compare from Java stack to equals and = =

Source: Internet
Author: User

Understanding stacks and stacks in Java


Stacks and heaps are places that Java uses to store data in RAM.

is different from C + +. Java itself actively manages stacks and heaps, and program apes cannot directly set stacks or heaps.
The Java heap is an execution-time data area from which the object of the class allocates space. These objects are created through directives such as new, NewArray, Anewarray, and Multianewarray, which do not require program code to be explicitly released.

Heap is responsible for garbage collection, the advantage of the heap is the ability to dynamically allocate memory size, the lifetime does not have to tell the compiler beforehand. Because it is dynamically allocating memory at execution time. Java's garbage collector will voluntarily take away data that is no longer in use. However, the disadvantage is that the access speed is slower due to the dynamic allocation of memory at execution time.


The advantage of the stack is that the access speed is faster than the heap. After register, stack data can be shared.

But the downside is. The data size and lifetime of the existing stack must be deterministic and inflexible. The stack mainly contains some basic types of variables (, int, short, long, byte, float, double, Boolean, char) and object handle.

Stack has a very important particularity, is the existence of data in the stack can be shared.


If we define at the same time:
int a = 3.
int b = 3;


The compiler handles int a = 3 first, and first it creates a reference to a variable in the stack. Then find out if there is a value of 3 in the stack. Suppose not found. Store the 3 in, then point A to 3.

then the int b = 3 is processed, and after the reference variable of B is created, B is pointed directly to 3 because there are already 3 values in the stack. In this case, A and B are all pointing to 3 at the same time.

Then. Suppose again to make a=4. The compiler will again search the stack for 4 values, assuming no, then store 4 in. And make a point to 4; If you already have one, point a directly at the address. Therefore the change of a value does not affect the value of B.


Note that such sharing of data with two object references at the same time points to an object such that the share is different. Because of the fact that A's change does not affect B, it is completed by the compiler, which facilitates space saving.

An object reference variable changes the internal state of the object. Affects an object reference variable as well.
String is a special wrapper class data.




Can be used:
String str = new String ("abc");
String str = "ABC";


In two forms, the first is to create new objects with new (). It will be stored in the heap. A new object is created each time the call is made. The other is to first create a String class object reference variable str in the stack, and then find out if there is no "abc" stored in the stack, assuming not. The "ABC" is stored in the stack and the STR points to "ABC", assuming that there is already "ABC" to direct str to "ABC".


Use the Equals () method when the values in the comparison class are equal. When you test whether the reference of two wrapper classes points to the same object, use = =, the following example illustrates the above theory.
String str1 = "abc";
String str2 = "abc";
System.out.println (STR1==STR2); True
You can see that str1 and str2 are pointing to the same object.


String str1 =new string ("abc");
String str2 =new string ("abc");
System.out.println (STR1==STR2); False
The new method is to generate different objects.

Each time one is generated.


So create multiple "abc" strings in a different way (string str1 = "abc"), in fact there is only one object in memory. This writing is advantageous and saves memory space. At the same time it can improve the execution speed of the program to some extent, because the JVM will take the initiative to decide whether it is necessary to create a new object based on the actual data in the stack. The code for string str = new String ("abc"). Creates new objects in the heap, regardless of whether their string values are equal, it is necessary to create new objects, which increases the burden on the program.


On the one hand, note that we are using a format such as String str = "ABC" when defining a class. Always think of course to feel that the object that created the string class is Str. Worry about the traps! The object may not have been created!

Instead, it might just point to an object that was previously created. It is only through the new () method that a new object is created each time.
Because of the immutable nature of the string class, when a string variable needs to change its value often. You should consider using the StringBuffer class to improve program efficiency.


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


The difference between equals and = = in Java

The data types in Java can be divided into two categories:
1. The basic data type, also known as the original data type. Byte,short,char,int,long,float,double,boolean
The comparison between them, the use of double equals (= =), the comparison is their value.


2. Composite data type (Class)
When they are used (= =) For comparison, the comparison is their memory address, so, unless it is the same new object, their comparative result is true, otherwise the result is false.

All of the classes in Java are inherited from the base class of object. A method of equals is defined in the base class in object, and the initial behavior of this method is to compare the memory address of the object, but in some class libraries this method is overwritten. such as string,integer,date in these classes where equals has its own implementation. It is no longer a comparison class in the heap memory of the storage address.


equals is compared between composite data types. In cases where the Equals method is not covered, the comparison between them is based on the address value of their location in memory, because the Equals method of object is also compared with the double equals sign (= =). So the result of the comparison is the same as the result of the double equals sign (= =).


<span style= "Font-family:microsoft yahei;font-size:12px;" >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");}} </span>


compile and execute the program, output: S1 = = S2 Description: S1 and S2 refer to the same String object-"Monday"!
2. A little bit more modification of the program, there will be more strange discovery:

<span style= "Font-family:microsoft yahei;font-size:12px;" >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");}}} </span>

We will create the S2 with the new operator
Program output:
S1! = S2
S1 equals s2
Description: S1 S2 cited two "Monday" string objects respectively


3. String buffer pool
It turns out that a string buffer pool is created when the program executes. When using S2 = "Monday" This expression is when creating a string, the program first looks for the same value object in this string buffer pool, in the first program. S1 was put in the pool first, so when S2 was created, the program found the S1 with the same value.
S2 refers to the object referenced by S1 "Monday"
In the second procedure, using the new operator, he explicitly tells the program: "I want a new one!" Don't be old. "So a new" Monday "Sting object is created in memory. Their values are the same. But the location is different. One swims in the pool and a rest on the shore. Oh. It's a waste of resources. What do you want to do separately?


4. Change the program again:

<span style= "Font-family:microsoft yahei;font-size:12px;" >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");}}} </span>

This increase: S2 = S2.intern ();
Program output:
S1 = = S2
S1 equals s2
Original (Java.lang.String's Intern () method "abc". The return value of the Intern () method is also the string "abc", which looks as if the method is of little use. But actually. It did a little trick: Check the string pool for the existence of "ABC" as a string, assuming it exists, return the string in the pool. Assumption does not exist. The method adds "ABC" to the string pool, and then returns its reference.
)


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


View source code Publication summary:

<span style= "Font-family:microsoft yahei;font-size:12px;" >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;    } </span>


The above paragraph is the equals source code of string, and we can find the secret through careful interpretation.

The Equals method of string overrides preserves the equality of object content addresses of two objects.

On this basis, adds a string that is equal to the value. What does that mean? Assume that the object in the equals bracket is not of type string. Then compare the memory address of the original object with the same. Suppose instanceofstring first turns this object into a string and then changes its value to a char array, that is, the following value, assuming that their char array is equal in length and that the char of the array is traversed one after the other. Assuming all the same, equals is true, otherwise false.





Compare from Java stack to equals and = =

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.