Java equals and "= =" Comparison

Source: Internet
Author: User

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, applying the double equals sign (= =), compares their values.
2. Composite data type (Class)
When they compare with (= =), they compare the storage address in memory, so unless it is the same new object, their comparison result is true, otherwise the result is false. All classes in Java are inherited from the base class of object, and 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, In these classes, date equals has its own implementation, rather than the comparison class's storage address in heap memory.
For the equals comparison between composite data types, the comparison between them is based on the address value of the location in memory where the Equals method is not covered, because the Equals method of object is compared with the double equals sign (= =). So the result of the comparison is the same as the double equals sign (= =).

1 public class TestString {
2 public static void Main (string[] args) {
3 String S1 = "Monday";
4 String s2 = "Monday";
5 if (S1 = = s2)
6 {
7 System.out.println ("S1 = = S2");}
8 else{
9 System.out.println ("S1! = s2");}
10}
11}

Compile and run the program, output: S1 = = S2 Description: S1 and S2 refer to the same String object-"Monday"!
2. A little more change to the program, there will be more strange discovery:

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 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
Originally, the program at run time will create a string buffer pool when using S2 = "Monday" expression is to create a string, the program first in this string buffer pool to find the same value of the object, in the first program, S1 was put into the pool, so when the S2 was created, The program found a S1 with the same value
S2 refers to the object referenced by S1 "Monday"
In the second procedure, the new operator was used, and he understood the telling 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 locations are different, one swimming in the pool and one resting on the shore. Alas, it is a waste of resources, obviously the same must be divided into what?

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");}
}
}


This time join: S2 = S2.intern ();
Program output:
S1 = = S2
S1 equals s2
Originally, (Java.lang.String's Intern () method "abc". The return value of the Intern () method is also the string "abc", which looks as if this method is of little use. But in fact, it did a little trick: Check the string pool for the existence of a string "abc", if present, return the string in the pool, if it does not exist, the method will add "ABC" to the string pool, and then return its reference.

Other than that:

One, the memory allocation strategy in Java and the comparison of heap and stack
1. Memory allocation policy
A. According to the compiling principle, there are three kinds of strategies for memory allocation in the program running, which are static, stacked, and heap-type.
Static storage allocation is the ability to determine at compile time the storage space requirements for each data target at run time, so that they can be allocated a fixed amount of memory at compile time. This allocation policy requires that the existence of mutable data structures (such as variable groups) not be allowed in the program code, and that nested or recursive structures are not allowed to appear. Because they all cause the compiler to not be able to calculate the exact storage space requirements.
B. A stack storage allocation can also be called dynamic storage allocation, which is implemented by a stack-like run stack. In contrast to static storage allocation, in a stack storage scenario, the requirements for the data area are completely unknown at compile time, only to be known when running, but when a program module is entered into the runtime, You must know the size of the data area required by the program module to allocate memory for it. As with the stack we are familiar with in the data structure, the stack storage allocation is distributed according to the principle of advanced post-out.
C. Static storage allocation requires that the storage requirements for all variables be known at compile time, and that the stack storage allocation requires that all storage requirements be known at the entrance of the process, while the heap storage allocation is specifically responsible for the memory allocation of the data structures that are not determined at compile-time or at runtime module entrances. such as variable-length strings and object instances. The heap consists of large chunks of available or free blocks, and the memory in the heap can be allocated and freed in any order.

2, heap and stack comparison
The above definition is summarized from the compiling principle of the textbook, in addition to static storage allocation, it is very inflexible and difficult to understand, the following aside static storage allocation, centralized comparison heap and stack:
From the heap and the function of the stack and the role of the popular comparison, the heap is mainly used to store objects, the stack is mainly used to execute the program. And this difference is mainly due to the characteristics of the heap and stack:
A. In programming, for example, C + +, all method calls are made through stacks, all local variables, formal parameters are allocated from the stack memory space. It's actually not an assignment, just up the top of the stack, like a conveyor belt in the factory (conveyor belt), stack pointer will automatically guide you to where you put things, All you have to do is put things down. When you exit a function, you can destroy the contents of the stack by modifying the stack pointer. This mode is the fastest, of course, to run the program. It is important to note that when allocating a data area for a program module that is about to be called, The size of this data area should be known in advance, but it is said that although the allocation is carried out at the time of the program running, the size of the allocation is determined, unchanged, and the "size of how much" is determined at compile time, not at runtime.
B. Heap is when the application is running to request the operating system to allocate its own memory, because of the memory allocation from the operating system management, so the allocation and destruction of time, so the efficiency of the heap is very low. But the advantage of the heap is that the compiler does not have to know how much storage space to allocate from the heap. It is also not necessary to know how long the stored data will stay in the heap, so there is greater flexibility in storing the data with the heap. In fact, object-oriented polymorphism, heap memory allocation is essential, because the required storage space for polymorphic variables can only be determined after the object is created at run time. In C + +, when you require an object to be created, you only need to compile the relevant code with the new command. When you execute the code, the data is saved automatically in the heap. Of course, to achieve this flexibility, there is a certain price to pay: it will take longer to allocate storage space in the heap! This is the reason we have just said that the inefficiency of the reasons, it seems that comrade Lenin said good, people's advantages are often also human shortcomings, human shortcomings are often also the advantages of people (halo ~).

3. Heaps and stacks in the JVM
A.JVM is a stack-based virtual machine. The JVM allocates a stack for each newly created thread. That is, for a Java program, it runs through the operation of the stack. The stack holds the state of the thread in frames. The JVM operates on the stack in only two ways: stack and stack operations in frames.
B. We know that the method that a thread is executing is called the current method of this thread. We may not know that the frame used by the current method is called the current frame. When a thread activates a Java method, the JVM presses a new frame into the Java stack of threads. This frame naturally becomes the current frame. During the execution of this method, this frame is used to hold parameters, local variables, intermediate calculation procedures, and other data. This frame is similar to the concept of the activity record in the compilation principle.
C. From this allocation mechanism in Java, the stack can be understood as a stack is a storage area established by the operating system for a process or thread (which is a thread in a multithreaded operating system) that has an advanced post-out feature.
D. Each Java application uniquely corresponds to a single JVM instance, with each instance uniquely corresponding to one heap. All instances or arrays of classes created by the application in the run are placed in this heap and shared by all threads of the application. Unlike C + +, allocating heap memory is automatically initialized in Java. The storage space for all objects in Java is allocated in the heap, but the reference to this object is allocated on the stack, that is, allocating memory from two places when an object is built, memory allocated in the heap actually establishes the object, and the memory allocated on the stack is just a pointer to the heap object (reference) Only.
D. The heap is the creation of objects, Java string Object memory implementation, in the heap opened up a very small memory, called string constant pool, used to hold a particular string object.
E. The Java stack in layman's terms
Java heap:
1. Dynamically allocating memory size during program operation
2.java garbage collector automatically reclaims data that is no longer in use
Java stack:
1. Stack data can be shared
2. The size of the data in the stack and the lifetime must be deterministic.
3. The stack mainly contains some basic types of variables (, int, short, long, byte, float, double, Boolean, char) and object references.

Second, string is a special wrapper class data. Can be used:
String str = new String ("abc");
The steps to create a string object using new are as follows, and a new object is created each time it is called.
1. First create a String object containing the specified content in the heap (not the constant pool) and point the string reference to the object.
2. Go to the string constant pool to see if there is an object that contains the content.
3. If so, the new string object is associated with the same object in the string constant pool.
4. If not, create a string object in the string constant pool that contains the content, and associate the objects in the heap with the newly created objects in the string constant pool.
The advantage of a string-specific memory mechanism is that the object is the same in a constant pool that only compares two strings, regardless of the size of the string and the speed of the comparison.
String str = "ABC";
1. Create an object reference variable to the string class first in the stack str
2. Then find out if the constant pool in the heap contains "ABC"
3. If not, store "ABC" in a constant pool and point str to "ABC"
4. If there is already "ABC" then direct str to "ABC".

Iii. Special Circumstances
Integers below 127 are equal
Integer i=100;
Integer j=100;
System.out.println (I==J); Print True
More than 128 is treated as a different object.
Integer i=200;
Integer j=200;
System.out.println (I==J); Print False

Java equals and "= =" Comparison

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.