Java basics: equals in String, declaration method, etc.

Source: Internet
Author: User

Java basics: equals in String, declaration method, etc.

 

Whether you are a beginner or veteran in programming, you must be very familiar with String, because we have learned the basics of java before, but is the String type as simple as we think? In fact, there are still many String-type knowledge points. Today I will discuss it with you. For some confusing things about String, I will not talk much about it... If you have any mistakes, please criticize and correct them. If you have any questions, please leave a message. I will modify or reply immediately

Through this blog, you will learn the following knowledge:

① = And equals difference, String a = abc and String a = new String (abc) heap memory and stack memory changes

② Difference between the two declaration Methods: String a = abc and String a = new String (abc)

③ The difference between abc. equals (abc) and a. equals (abc). analyze why abc. euqals (str) can avoid null pointers from the source code.
④ The value of the String object cannot be modified. Why can the value be assigned again and changed?
⑤ Difference between String a; and String a = null, String a =
⑥ String s1 = new String (s1); String s2 = new String (s1); how many objects are created in total?
1. Difference Between = and equals, the heap memory and stack memory of String a = abc and String a = new String (abc)
Let's first look at a piece of code
public class StringDemo {public static void main(String[] args) {String str1 = hello;String str2 = new String(hello);String str3 = str2;System.out.println(str1==str2:+(str1==str2));System.out.println(str1==str2:+(str1==str3));System.out.println(str1==str2:+(str2==str3));}}
The output is as follows:
Why? Why is it printed like this? In the above example, the content of str1, str2, and str3 is the same, but the comparison results are equal and some are not equal. Why? First, let's take a look at the memory distribution diagram above.
We can clearly find that the content of each String object is actually saved to the heap memory, and the content in the heap is equal. However, for str1 and str2, the address heap memory address is different, so although the content is equal, the address value is not equal, "=" is used for numerical comparison, so str1 and str2 are not equal, because str2 and str3 point to the same memory address, so str2 and str3 are equal. Therefore, "=" is used to compare the address values. So how can we determine whether the content of two strings is equal? Let's first look at an example.
public class StringDemo {public static void main(String[] args) {String str1 = hello;String str2 = new String(hello);String str3 = str2;System.out.println(str1 equals str2:+(str1.equals(str2)));System.out.println(str1 equals str2:+(str1.equals(str3)));System.out.println(str1 equals str2:+(str2.equals(str3)));}}
The running result is as follows:
Because the equals method is used to compare the content, the returned results here are true. To sum up the above two examples, we can sum up the difference between = and equals: "=" is used for numerical comparison, and "=" is used in String to compare the address values, equals compares String content.
2. The difference between the two declaration methods is that a String is a String's anonymous object. Why? We can use hello. the print result of equals (hello) is true, because "hello" can pass "hello ". equals () directly calls the method in String, so for String str1 = hello; in fact, it is to grant the right to use a heap memory space opened in the heap memory to the str1 object, another advantage of using this method is that if a string has been referenced by a name, the space will not be re-opened when the same string is declared in the future, what does it mean to continue using the heap memory that has been opened up? The code of this example is as follows:
public class StringDemo {public static void main(String[] args) {String str1 = hello;String str2 = hello;String str3 = hello;System.out.println(str1==str2: + (str1 == str2));System.out.println(str1==str3: + (str1 == str3));System.out.println(str2==str3: + (str2 == str3));}}
The output is as follows:
Sorry, what is the situation? The above we just concluded that = is the address value compared in String. Why are the printed results true? In fact, this is a shared design in java. This design idea is to form an object pool in java and store multiple objects in this pool, if the newly instantiated object has already been defined in the pool, it will not be redefined, but will be taken out from the pool for further use. String adopts this design. There is a String pool in the Java Runtime Environment, which is maintained by the String class. When executing the statement String str1 = hello, first check whether the String hello exists in the String pool. If yes, the String hello is directly assigned to str1. If no, a new String hello is created in the String pool, then assign it to str1. When executing the statement String str = new String (hello), a new String hello is directly created regardless of whether the String pool contains the String hello (Note: The new String hello is not in the String pool ), and then pay it to str. The efficiency of the previous statement is high, and the efficiency of the latter statement is low, because the new string occupies memory space. String str = new String () creates an empty String, which is the same as String str = new String.
Let's sum up: the strings created with quotation marks are constants, and they have been stored in the String pool during the compilation period. The new String () the created object is stored in the heap memory (head) and is created during runtime.
Through the comparison of the above two implementation methods, you can know which method is more suitable. For string operations, you can directly assign values, instead of using the constructor to pass strings, this prevents spam.
3. What is the variable content of a string? Some may say that you are not here to fool me. Why is this not nonsense? Let's take a look at the example code as follows.
public class StringDemo {public static void main(String[] args) {String str=hello;str=str+ world!;System.out.println(str=+str);}}
Print results
Some people may say that you think it has changed? Starting with hello, followed by hello world !. The program running result shows that the content of the String object has been modified, but is the content modified? The following uses a memory distribution chart to describe the meaning of the string content that cannot be changed.
It can be clearly found that the change of the content of a String object is actually completed through the disconnection of the memory address-connection change, but the content of the String itself has not changed.
4. What is the difference between abc. equals (str) and str. equals (abc)? analyze why abc. euqals (str) can avoid null pointers from the source code.
We should have heard of abc. equals (str), which can avoid null pointers. Why? Many people may write this frequently, but do not understand the principle? Let's start with an example.
public class StringDemo {public static void main(String[] args) {String str1 = hello;String str2 = null;System.out.println(str1.equals(str2));}}

Let's take a look at the code section.
public class StringDemo {public static void main(String[] args) {String str1 = hello;String str2 = null;System.out.println(str2.equals(str1));}}
The only difference from the above Code is that the above is str1.equals (str2), here is str2.equals (str1), let's see what the printed results will look like.
I said it, uncle. I reported a null pointer. Why? Why does st1.equals (str2) print false, while str2.equals (str1) returns a null pointer, which is not scientific. If you want to know the cause but the source code is the most convincing, let's take a look at the equals source code in the String class. Let's take a look at the equals source code in the String class as follows:
/*** Compares this string to the specified object. the result is {@ code * true} if and only if the argument is not {@ code null} and is a {@ code * String} object that represents the same sequence of characters this * object. ** @ param anObject * The object to compare this {@ code String} against ** @ return {@ code true} if the given object represents a {@ code String} * equivalent this string, {@ Code false} otherwise ** @ see # compareTo (String) * @ see # define signorecase (String) */public boolean equals (Object anObject) {// determine whether to compare with yourself if (this = anObject) {return true;} // determine whether the passed anObject is a String-type instance 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; // compare while (n --! = 0) {if (v1 [I]! = V2 [I]) return false; I ++;} return true ;}} return false ;}
From the source code, we can first determine whether it is compared with ourselves, and then determine whether the passed object is a String-type instance, note that the keyword instanceof is used to determine the instance of the class of an object. Note that this is an instance. We directly use String str2 = null. In this case, str2 is not a String-type instance, if you don't believe it, you can verify it. Because String str2 = null declares a String-type str2 and applies for an address in the memory, but this address does not point to any reference address, therefore, when executing this judgment, the if statement directly jumps out and returns false. So we won't report the empty pointer...
5. Differences between String a; and String a = null, String a =
String a; declare a string-type a, that is, the memory address is not applied for, nor is there any point to the reference address in the memory;

String a = null; declare a string type a and apply for an address in the memory, but this address does not point to any referenced address;

String a =; declare a string-type a, which applies for an address in the memory and points to a reference address that references the String;
String a = null, String B = hello; system. out. println (a + B); Output nullhello;
6. String s1 = new String (s1); String s2 = new String (s1); how many objects are created in total? It is not difficult to understand this problem through the above analysis. First, String s1 = new String (s1), we can see that (s1), at this time s1 is read as a constant, therefore, an object will be created in the String pool and new will be created in the heap memory (head). Therefore, execute String s1 = new String (s1) two objects are created, and when String s2 = new String (s1) is executed, (s1) is also read as a constant, however, because s1 already exists in the String pool, no object will be created in the String pool this time, but an object must be created when new is executed, therefore, an object is created when String s2 = new String (s1) is executed. See the following two pieces of code: the first piece of code: String s1 = new String (s1); // create two objects, one reference
String s2 = new String (s1); // creates an object, and creates an object and references each execution.
Code 2: String s3 = xyz; // create an object and a reference
String s4 = xyz; // no object is created, but a new reference is created.
The analysis of the String type is over now. After work, I added a class meeting to complete this blog. If you think it is useful to you, I don't mind leaving a comment. Haha, today is Friday. Have a good weekend ....

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.