Java String class learning (I) Overview and common methods, javastring

Source: Internet
Author: User

Java String class learning (I) Overview and common methods, javastring


(Expansion: Api:The application interface provided by the programming language .)

I. Overview:

We usually post online. The title, content, and QQ chat content of the post are strings. Because it is very common, programming languages often encapsulate strings into one class, implement methods, and add functions to facilitate our daily operations during programming.

In Java, the String is encapsulated into the String class under the java. lang package.

Looking at javaapi, we found that string is modified by final. It indicates that the class 'string' cannot have subclasses. (That is, the function of string operations in the class cannot be rewritten .)

StringClass represents a string.All character strings (such as abc) in Java programs are implemented as such instances. That is to say,InJavaAs long as the content summarized by "" is a string, it is a string.

Check the java api and we find that the string class has no constructor, that is:

String s = new String (); equivalent to: String s = "";

In this way, we can easily find the second method is easier, so the first initialization method is rare.

Below is a small example:

String s1 = "abc ";

For such a string example, s1 is a class type variable, which must point to an object. So "abc" is an object. Therefore, a string (that is, all enclosed by double quotation marks) is a special object.

The biggest character of a string: (object) cannot be changed once initialized. (String constant)

String s = "abc ";

S = "kk ";

System. out. println (s );

The output is kk.

Some may have questions, saying it cannot be changed, but why does it print kk?

As mentioned above, s is a class variable, and s is variable. It points to a string object (or constant) "abc" at the beginning ", "abc" is the string object we are talking about. Its content will not be changed by other things. The same is true for "kk. S is changed, and abc and kk are not changed ". Both "abc" and "kk" exist in the memory.


Let's look at the api. We found that the string can also be passed in the string constructor with parameters.


String s = "abc ";

String s1 = new String ("abc ");

The usage is the same, but there are differences:

System. out. println (s = s1); // false, because "abc" is an object and new String () is another object. The two address values are different.

System. out. println (s. equals (s1); // true,Although StringParent Class ObjectClass equals ()The method compares the address value, but the StringClass describes the method of the parent class. This method is used to determine whether the content of a string is the same..

Interview Questions:

String s = "abc ";

String s1 = new String ("abc ");

What is the difference?

S has an object in the memory.

S1There are two objects in the memory.

A brief description of the String constant pool

Strings are stored in a memory called a constant pool and are stored in arrays like "a", "B", and "c.

We all know that strings are composed of character arrays.

When we store "abc", the memory is placed in the array, and then we store another "efg". The memory also splits them into arrays, when we store the "abf" string, the memory will find the corresponding character in the array to spell the string.

A small exercise is extended:

String s1 = "abc ";

String s2 = new String ("abc ");

String s3 = "abc ";

System. out. println (s1 = s2 );

System. out. println (s1 = s3 );

The answer is output respectively:



We have already mentioned the first part.

So what is the second one?

S1 points to an object string, and s3 also points to a string. The string created by s1 already exists in memory. A string is a special object stored in a constant pool. S3 finds that the characters in the string already exist in the memory during initialization, because the string content is the same (the character array is the same), s3 will no longer open up the memory space independently.

If s3 re-opens the memory space, it will produce a waste of space: the string already exists and will not change, so it will not open up space.

Ii. Common Methods

The String class is used to describe String objects. It provides multiple methods to operate strings. What are common operations?

1. Get

1. 1. Number of characters in a string (length)

Int length ();

Note: The array also has length, but the length of the array is an attribute with no parentheses.

1.2 obtain a character at the position based on the position.

Char charAt (int index) when accessing a character string that does not exist, the character string's foot mark is out of bounds. Exception: StringIndexOutOfBoundsException.

1.3 obtain the position of the character in the string based on the character.

Int indexOf (int ch); The received parameter is an ascii code, and the return value is the location where ch first appears in the string.

Int indexOf (int ch, int fromIndex): obtains the position of ch in the string starting from the specified position of fromIndex.

If the access fails (this character is not in the string),-1 is returned.

1.4 obtain the position of the string in the string based on the string (find a small string in a large string)

Int indexOf (String str); The received parameter is an ascii code, and the return value is the position where str first appears in the String.

Int indexOf (String str, int fromIndex): obtains the position of str in the String starting from the specified position of fromIndex.

1.5 reverse returns the position of the character in the string based on the Character

Int lastIndexOf (int ch); The received parameter is an ascii code, and the return value is the location where ch first appears in the string.

Int lastIndexOf (int ch, int fromIndex): obtains the position of ch in the string starting from the specified position of fromIndex.

1.6 obtain the position of the string in the string based on the reverse direction of the string

Int lastIndexOf (String str); The received parameter is an ascii code, and the return value is the position where str appears for the first time in the String.

Int lastIndexOf (String str, int fromIndex): obtains the position of str in the String starting from the position specified by fromIndex.

2. Judgment

2.1 indicates whether the string contains a substring.

Boolean contains (String str );

Special variant: indexOf (String str) can be used to locate the first occurrence of str. If-1 is returned, this str does not exist in the String. Therefore, it can also be used to determine whether a specified string is contained. In addition, this method can be used to determine and obtain the location of the occurrence.

Application: if it is only for judgment, use contains. If you want to judge and obtain the location, use indexOf

2.2 whether the string contains content

Boolean isEmpty (); the principle is to determine whether the length is 0

2.3 whether the string starts with the specified content

Boolean startsWith (String str)

2.4 whether the string ends with the specified content

Boolean endsWith (String str)

2.5 determine whether the content of the string is the same

Boolean equals (String str) describes the equals method in the Object class.

2.6 check whether the string content is the same and ignore the case sensitivity.

Boolean inclusignorecase ()

3. Conversion

3.1 convert character arrays into strings

Constructor: In a string constructor, a constructor is used to input character arrays,

String (char [] value)

During string initialization, the character array can be converted to a string.

It also has a heavy-load constructor.

String (char [] value, int offset, int count): converts a portion of the character array into a String.

The second parameter is the offset, and the third parameter is the number.

Likewise, the constructor of a byte array is the same. Only an additional shard set

Static function static String copyValueOf (char [] data). Note that it is static because it does not operate on special data internally. He also has an overload function to convert a part of the character array into a string.

Static String copyValueOf (char [] data, int offset, int count)

Static String valueOf (char [] data)


3.2 convert a string to a character array **

Search api skills: It is certainly not constructed. If it is converted into an array, there will be a return value, and it is a char type array, so you can find it based on the return value type of the method.

Char [] toCharArray (). Why didn't I input a string parameter here? Because the method is called by an object, the object that calls this method here is a string, so this is hidden in brackets.

3.3 convert byte arrays into strings (IO)

String (byte [] value)

String (byte [] value, int offset, int count) converts part of the byte array into a String

3.4 convert a string to a byte array

Byte [] getBytes ()

3.5 convert basic data into strings.

Static String valueOf (int)

Static String valueOf (double)

Example: String. valueOf (3) = "3" = 3 + ""



Special: encoding tables can be specified during conversion of strings and byte arrays.



4. Replace

String replace (char oldChar, char newChar), note that a new String is returned, because once a String is created, it cannot be modified, so a new String is returned.

If the character to be replaced does not exist, the original string is returned. However, it is troublesome to replace such a character with a single character. Java provides us with another method.

String replace (CharSequence target, CharSequence replacement) This method can directly receive and replace strings. The first parameter is the old string, and the last parameter is the new string.

There are two other methods:

String replaceAll (String regex, String replacement );

String replaceFirst (String regex, String replacement );

Because regular expressions are involved, you do not need to learn them for the moment. You can simply replace the specified rule.

5. Cutting

Note: Separate a string into several strings and return a string array.

String [] split (String regex );

The input parameters are also a rule, but this rule is a bit special. You do not need to specify a rule (Regular Expression). You can also write a general string.

String s = "zhangsan, lisi, wangwu ";

String [] arr = s. split (",");

For (intx = 0; x <arr. length; x ++ ){

System. out. println (arr [x]);


Note: The split is not equal to the get. In this example, the string contains ",", but the obtained array does not contain ",". The standard string of the split string cannot be obtained.


6. substring. Obtain a part of the string (which can be placed in the get)

String substring (int beginIndex): from the specified position to the end.

String substring (int beginIndex, int endIndex) contains the header, not the end.

If the script does not exist, an exception occurs.

In the case of cutting, We Can index the footer of a comma and use the method here to get the name. It is troublesome, without cutting fast.

7. Conversion

Converts a string to uppercase or lowercase.

String toUpperCase ();

String toLowerCase ();

8. Remove Spaces

Remove multiple spaces at both ends of the string

String trim ();


9 Comparison

Compare two strings in natural order (dictionary order)

Int compareTo (String str)

There are three results: greater than, less than, or equal

If the object is equal to the input parameter, 0 is returned.

If the object is smaller than the input parameter, a negative number is returned.

A positive number is returned if the object is greater than the input parameter.

The returned value is the result of comparing the ASCII values of the characters corresponding to the same character of the two strings. If the two strings are the same, the comparison will continue until the comparison is different. If the two strings are different, the output result will be displayed, do not continue the comparison.

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: 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.