Foreword

One after another, learning Java from 0 will have a wider path to mastering a language. Both .NET and Java will take care of it. Although the road is still difficult, it is a man-made thing. Because Java and C # have similar syntax, I wo n’t repeat the basics. All articles in the Java series will be based on my personal thoughts after reading articles and blogs. Some will be compared with C # syntax, and some are brand new. Concept, explain the complete basic series, and then enter the data structure and in-depth study of the JVM, I will record in detail, all series of syntax are based on Java8, let’s start.

String creation

There are four ways to create a string in Java. One is to create a string directly through the new operator, the other is to create a character array, the third is to extract a character array, and the fourth is to define a string variable. Let ’s take a look Pass

(1) The new operator creates a string

String str = new String ("Jeffcky" );
System.out.println (str);

Java_entry_series[1]_string_creation_method_0.png

(2) String object to create a String object

char a [] = {'j', 'e', ​​'f', 'f', 'c', 'k', 'y' };
String str = new String (a);
System.out.println (str);

Java_entry_series[1]_string_creation_method_1.png

(3) Extract the character array to create a String object

In the first way, the character array is directly obtained through the new operator, and the string object created by the new operator is also overloaded, as follows:

char a [] = {'j', 'e', ​​'f', 'f', 'c', 'k', 'y' };
String str = new String (a, 0,4 );
System.out.println (str);

Java_entry_series[1]_string_creation_method_2.png

The first parameter of this overloading method is the character data of the operation, the second parameter is the offset, which means where to intercept the character array, and the third parameter is count, which means we have to read Characters.

(4) String constant reference assignment to create a string

This method is also the most commonly used way to create string variables, as follows:

String str = "Jeffcky" ;
System.out.println (str);

Java_entry_series[1]_string_creation_method_3.png

Strings are equal

Judging whether strings are equal is handled differently in Java and C #. Next we will compare the processing in C # and Java. Let’s first take a look at the difference between C # and Java in the way of judgment, as follows for C #

“==” and equals

 

 

        static  void Main (string [] args)
        {
            string str1 = new string ("Jeffcky" );
            string str2 = new string ("Jeffcky" );
            Console.WriteLine (str1 == str2);
            Console.WriteLine (str1.Equals (str2));
            Console.ReadKey ();
        }

 

 

Let’s take a look at the same judgment method in Java:

 

 

public static void main (String [] args) {
        String str1 = new String ("Jeffcky" );
        String str2 = new String ("Jeffcky" );
        System.out.println (str1 == str2);
        System.out.println (str1.equals (str2));
}

 

 

Java_entry_series[1]_string_creation_method_4.png

By printing the results in C # and Java as above, presumably we know the difference. In C # == directly judges whether the values ​​are equal for value types, and for reference types, especially strings, the Equals method is rewritten to directly compare strings. Value, so the above prints true. In C #, if you want to compare whether the address of the reference type is equal, use the ReferenceEquals method. So if the above demo code in C # wants to get the result in Java, the demo code becomes as follows:

 

 

static void Main (string [] args)
 {
     string str1 = new string ("Jeffcky" );
     string str2 = new string ("Jeffcky" );
     Console.WriteLine (ReferenceEquals (str1, str2));
     Console.WriteLine (str1.Equals (str2));
     Console.ReadKey ();
}

 

 

Let ’s look at the comparison of “==” for strings created by the new operator in Java as false. This is because the addresses of two identical string objects created by the new operator are different. From this we can see: == is not a comparison of string values, because “==” only checks the reference equality of two strings, meaning that they refer to the same object. If the above Java code is modified as follows, then the two strings are equal by “==” comparison:

 

 

public static void main (String [] args) {
        String str1 = "Jeffcky" ;
        String str2 = "Jeffcky" ;
        System.out.println (str1 == str2);
        System.out.println (str1.equals (str2));
 }

 

 

Java_entry_series[1]_string_creation_method_5.png

After we have modified the above, we use “==” to judge that str1 and str2 point to the address of the same object Jeffcky on the heap. Then we can see at a glance the following modifications

 

 

public static void main (String [] args) {
        String str1, str2;
        str1 = "Jeffcky" ;
        str2 = "Jeffcky" ;
        System.out.println (str1 == str2);
        System.out.println (str1.equals (str2));
}

 

 

Let’s explain it one line at a time. The first string str1 and str2 are referenced as null. The second line creates an object named Jeffcky on the heap. At this time, the reference address is assigned to str1, and the third line is already the same on the heap. The string of the object directly assigns the reference address to str2, so the referenced objects of str1 and str2 print true at this time. Next, let’s look at the equals method. The favorite is to view the source code directly in Java. Let’s look at the equals method implementation, as follows:

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

 

 

It is not difficult to see from the source code above: The String class overrides the equals method inherited from Object. This method compares two strings character by character and ignores their reference addresses. That is, if the length and character order are equal, they are considered equal. .

Object equals

Above we discussed that the equals method in the string overrides the equals method in the Object class, so what is the logic of the equals method comparison in the Object class? Let’s take a look at the following code:

 

 

import   java.util.Objects;

public  class Main {

    public  static  void main (String [] args) {
        String string1 = "using objects equals" ;
        String string2 = "using objects equals" ;
        String string3 = new String ("using objects equals" );

        System.out.println (Objects.equals (string1, string2));

        System.out.println (Objects.equals (string1, string3));

        System.out.println (Objects.equals ( null , null ));
        System.out.println (Objects.equals ( null , string1));
    }
}

 

 

Java_entry_series[1]_string_creation_method_6.png

For the above print results, we analyze the equals source code in the Object class to analyze it as follows:

 public  static  boolean equals (Object a, Object b) {
         return (a == b) || (a! = null && a.equals (b));
 }

From this we conclude that the equals in the Object class are static methods. First, they are compared using their addresses, that is, “==”. If the two strings are equal, the method returns true. At the same time, it returns true if both parameters are null, and false if only one parameter is null. Otherwise, it just calls the equals method of the class of the passed parameter type, and the above is the equals method of the String class. This method is case sensitive because it calls the equals method of the String class internally.

Summary

In this article, we have introduced the comparison of strings in Java in detail. There may be misunderstandings among beginners like me. If you do n’t know the internal implementation, you should use equals method instead of “==” or use Object for judging the equality of strings The static method of the class equals (because its built-in will call the equals method of the object), because “==” is to compare whether the references are equal,  of course using” == “for value types is no problem.

Java entry series [1] string creation method

Java entry series [2] string features

Java entry series [3] stringbuilder string buffer

Java entry series [4] packaging class

Java entry series [5] inheritance abstract classes interfaceson

Java entry series [6] Principles of dynamic array

Java entry series [7] collection arraylist

Java entry series [8] principles of doubley linked list alogrithm

Java entry series [9] linkedlist source code analysis

Java entry series [10] Hash algorithm principle

Java entry series [11] Hashtable source code analysis

Java entry series [12] Hashcode and equals

Java entry series [13] Principles of the read-black tree algorithmn method

Java entry series [14] Hashmap source code ananlysis

 

Orignal link:https://www.cnblogs.com/CreateMyself/p/11437018.html