java-Basics-Common APIs (Equals,tostring method, String Class)

Source: Internet
Author: User

Java API and the object class

Java API -applicatio (application),Programming (program),Interface (interface)

The Java API is the class that is provided to us in the JDK, which encapsulates the underlying code implementation, and we don't need to be concerned about how these classes are implemented, just how these classes can be used.

an overview of the object class

The object class is the root class in the Java language, which is the parent class of all classes . All of the method subclasses described in it can be used. All classes when creating objects, the final parent class to find is object.

The Equals method and the ToString method

The Equals method, which is used to compare two objects , is actually compared with the memory address of two objects. The Equals method inside the object class is used internally by the = = comparison operator.

In development, to compare two objects is the same, often based on the value of the property in the object comparison, that is, in development often requires subclasses to override the Equals method to compare the property values of the object. The following code shows:

/*describe a person in this class, and define the function according to age to determine whether it is a peer because you want to compare the properties of the specified class, as long as you override the Equals method in object to compare the property values of the class in the method body*/classPersonextendsobject{intAge ; //The equals method of the replication parent class to achieve its own comparison     Public Booleanequals (Object obj) {//determines whether the object that is currently calling the Equals method is the same as the object passed in        if( This==obj) {            return true; }        //determines whether the passed in object is a person type        if(! (objinstanceofPerson )) {            return false; }        //Transform obj down to a perosn reference, accessing its propertiesPerson p =(person) obj; return  This. Age = =P.age; }}
Note : When you are copying the Equals method in an object, be sure to note that the arguments of the public boolean equals (object obj) are of type object,
When invoking the properties of an object, type conversions must be performed before the conversion.

The instanceof operator is used to indicate at run time whether an object is an instance of a particular class. Instanceof is indicated by returning a Boolean value,
Whether this object is an instance of this particular class or its subclasses

The tostring method, which returns the string representation of the object, is actually the type of the object [email protected]+ memory address value.

class extends object{    int age ;     // override the ToString method based on the property of the person class     Public String toString () {        return ' person [age= ' + Age + '] ';    }}

String class

Look up the description of the string class in the API and discover that the string class represents the strings. All string literals (such as "ABC") in a Java program are implemented as instances of this class.

Once the string is determined, the string is generated in the memory area. The string itself cannot be changed, but the address value recorded in the STR variable can be changed.

The essence of a string is an array of characters.

String s3 = "abc";  There is only one object in memory,  new string ("abc") in the string constant pool;  There are two objects in memory, a new object in the heap, and a character string itself object System.out.println (S3==s4); // false System.out.println (S3.equals (S4)); // true,

Because string overrides the Equals method, it establishes the same basis for the string's own judgment (judged by the characters in the string object)

L S3 is created with only one object in memory. This object is in the string constant pool

L S4 Created, there are two objects in memory. A new object in the heap, a string itself object, in a string constant pool

String String Type: String is a reference type, and at the beginning of the design, the virtual machine made a special optimization for him, saving the string in a string in a long pool inside the virtual machine. Once we are creating a string, the virtual opportunity first checks the constant pool to see if the string has been created, and if so, a direct reference. because of the optimizations described above, the string object is guaranteed that the object's content cannot be changed since it was created, so any changes to that string will create a new object. When comparing strings, it is common practice to use the Equals method, where the string overrides the Equals method of object. Used to compare string content consistency. When we compare a string variable to a literal, we do not call the variable's. Equals method, and the second is the. Equals method that should invoke the literal. The reason is that we cannot guarantee that the variable is not NULL, and if the variable is NULL, a null pointer exception is thrown. Causes the program to exit. string's own implementation of the comparison method, which ignores the string case problem: Equalsignorecase methodString s3 = "Hello";if ("Hello". Equelsignorecase (S3)) {System.out.println ("string content is" Hello ");}else{System.out.println ("String content not Equal");}

String Class construction method

String S1 =NewString ();//create string object with no content in string        byte[] Bys =New byte[]{97,98,99,100}; String S2=NewString (bys);//creates a string object that takes an array element as the contents of a string
String s3 =NewString (bys, 1, 3);//creates a string object that takes a subset of the array elements as the contents of the string,
The parameter offset is the starting index position of the array element, and the parameter length is a few elements Char[] CHS =New Char[]{' A ', ' B ', ' C ', ' d ', ' e '}; String S4=NewString (CHS);//creates a string object that takes an array element as the contents of a string

String S5 =NewString (CHS, 0, 3);//creates a string object that takes a subset of the array elements as the contents of the string,
The parameter offset is the starting index position of the array element, and the parameter count is a few elementsString S6=NewString ("abc");//creates a string object with the content of the strings ABC

Method lookup for the String class

A string is an object, and its method must be defined around the data that operates on the object.

int Length () method, which returns the lengths of this string

String str = "ABCDE"; int len = str.length (); System.out.println ("len=" +len);

substring (int beginindex) method returns a new string that is a substring of this string (all characters to the end of the specified position)

substring (int beginindex, int endindex) method returns a substring of the new string, the string of the second character (the specified position begins at the end of the specified position)

String str = "ABCDE"// Returns a new string that contains all characters starting at the specified position to the end of the string s2 = str.substring (2, 4); // returns a new string with the content starting at the specified position to the end of all characters System.out.println ("str=" +str); System.out.println ("s1=" +S1); System.out.println ("s2=" +s2);

startwith (String prefix) tests whether this string starts with the specified prefix

endsWith (string suffix) tests whether this string ends with the specified suffix

String str = "Stringdemo.java"; Boolean B1 = Str.startswith ("Demo"); // determines whether to start with the given string boolean b2 = Str.startswith ("String"); Boolean b3 = Str.endswith ("java"); // determines whether to end with the given string

Contains (charsequence s) tests whether to include the specified string returns TRUE or False Boolean

The indexOf (string str) test contains the specified string, containing the index that returns the first occurrence of the string, not including the 1 int

String str = "ABCDE"; int // determines whether the specified string is included, returns the index of the first occurrence of the string, or 1 if it is not included boolean b2 = Str.contains ("BCD"); // determines whether to include the specified string, contains a return of true, and does not contain a return of false

getBytes () encodes this string into a byte sequence using the platform default character set and stores the result in a new byte array byte[]

ToCharArray () converts a string to a new character array char[]

String str = "ABCDE"; Char [] CHS = Str.tochararray ();  Convert to a character array  byte[] bytes = Str.getbytes (); //Convert to byte array

Equels (object anobject) compares this string to the specified object by a Boolean

equelsignorecore (string anotherstring) compares this string to another string without regard to case Boolean

String str = "ABCDE"= "ABCDE"= "Hello"; Boolean B1 = str.equals (str2);  Trueboolean b2 = Str.equals (STR3); //false

toString () returns the object itself (it is already a string)------------------------gets the contents of the string object

New String ("Hello"); System.out.println (Str.tostring ()); System.out.pintln (str);
// when you print a reference type variable directly, the default invocation of the type is overridden by the ToString method

java-Basics-Common APIs (Equals,tostring method, String Class)

Related Article

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.