"A string explanation of Java"

Source: Internet
Author: User

Java's string classes are often used in development, which shows the importance of string. After a careful and careful study of the Java string class. Discovered the shortcomings of the string used in his previous development, and featured this blog to record his learning summary of string.

First, string is not part of 8 basic data types, and string is an object. Because the default value of the object is NULL, the default value of string is also null, but it is a special object that has some features that other objects do not have.

A string is actually the data stored using a character array . The defined character array can be clearly seen from the source.


String under the Java/lang package, Java imports the Lang packet by default, so you don't have to import it when you use the String class.

1. How to create


(1) string Ok1=new string ("OK");
(2) String ok2= "OK";
I believe a lot of people know these two ways of defining strings, but the difference between them is so much clearer. Draw the memory of these two strings:
650) this.width=650; "id=" aimg_286 "src=" http://techfoxbbs.com/data/attachment/forum/201505/21/ 110057lselzjk9sq539lzj.png "class=" Zoom "width=" 488 "alt= " 110057lselzjk9sq539lzj.png "/>
String Ok1=new string ("OK"). First, a chunk of memory is requested in the heap memory string Ok,ok1 points to its memory block object. It also checks whether the string constant pool contains an OK string, and if not, adds OK to the string constant pool. Therefore, a new String () may create two objects.
String ok2= "OK". Check that the string constant pool contains an OK string, and if there is a direct point, no then add an OK string to the string constant pool and point to it. so this method creates at most one object, and it is possible not to create an object
so String Ok1=new string ("OK");//Created two objects
String ok2= "OK";//No object created

Two exercises to see if you really understand
1. How many objects are created by the following code?

    1. String temp= "Apple";

    2. for (int i=0;i<1000;i++)

    3. {

    4. Temp=temp+i;

    5. }

Copy Code

Answer: 1001
2. How many objects are created by the following code?
    1. String Temp=new string ("Apple")

    2. for (int i=0;i<1000;i++)

    3. {

    4. Temp=temp+i;

    5. }

Copy Code

Answer: 10022. Match equal
Using the string class often requires a comparison of two strings to see if they are equal. This is also the = = and equals two options, the two methods are very different, we may be mistaken, the following we have a detailed explanation of both methods.
The first thing to understand is the use of these two methods:
compares the values in a class with Equals (), compares the two wrapper class references to the same object with = =
Equals () is a good understanding of whether the values are equal. and = = To see if they belong to the same object. The following examples illustrate the use of = =

Understand this concept first: the constant pool is used in Java to save theThe compilation period has been determined, a copy of the data in the compiled class file. The main view is whether the compile-time string can be determined.
Situation One:
    1. String ok= "OK";

    2. String Ok1=new string ("OK");

    3. System.out.println (OK==OK1);//fasle

Copy Code

Obviously not the same object, a pointer to a constant pool of strings, a block of heap memory pointing to new, new string is not determined at compile time. So output false
Situation Two:
    1. String ok= "Apple1";

    2. String ok1= "Apple" +1;

    3. System.out.println (OK==OK1);//true

Copy Code

Compile-time OK and Ok1 are both deterministic, strings are apple1, so both OK and Ok1 point to String apple1 in the string constant pool. Points to the same object, so true.
Situation Three:
    1. String ok= "Apple1";

    2. int temp=1;

    3. String ok1= "Apple" +temp;

    4. System.out.println (OK==OK1);//false

Copy Code

Mainly see whether OK and Ok1 can be determined at compile time, OK is OK, put in and point to the constant pool, and Ok1 contains variables resulting in uncertainty, so not the same object. Output False
Situation Four:
    1. String ok= "Apple1";

    2. final int temp=1;

    3. String ok1= "Apple" +temp;

    4. System.out.println (OK==OK1);//true

Copy Code

OK, plus final allows Ok1 to be determined at compile time, so output true
Situation Five:
    1. public static void Main (string[] args) {

    2. String ok= "Apple1";

    3. Final int temp=gettemp ();

    4. String ok1= "Apple" +temp;

    5. System.out.println (OK==OK1);//false

    6. }


    7. public static int Gettemp ()

    8. {

    9. return 1;

    10. }

Copy Code

OK is the same as OK. And Ok1 cannot be sure that it needs to run code to get temp, so it is not the same object, output false.

3.Intern () method
The previous section of Chang in Java is used to hold a copy of the compiled class file that was determined at compile time.
But we can extend the constant pool through the intern () method.
Intern () is a method of extending a constant pool, and when a string instance str calls the Intern () method, Java checks for the same string in the constant pool, returns its reference if there is one, and if not, adds a STR string to the constant pool and returns its reference.
Such as:
    1. String ok= "Apple";

    2. String Ok1=new string ("Apple");

    3. System.out.println (OK==OK1);//false

    4. Ok1=ok.intern ();//Get a reference to a constant pool OK

    5. System.out.println (OK==OK1);//true--points to the same object

Copy Code



650) this.width=650; "id=" aimg_287 "src=" http://techfoxbbs.com/data/attachment/forum/201505/21/ 110243ijjzz1rb586u8xgv.png "class=" Zoom "width=" 317 "alt= " 110243ijjzz1rb586u8xgv.png "/>
4.String Common Methods
(1) Length ()The length of the string
Example: Char chars[]={' A ', ' B '. ' C '};
String S=new string (chars);
int Len=s.length ();

(2) charAt ()Intercept a character
Example: Char ch;
Ch= "abc". CHARAT (1); Return ' B '
(3) getBytes ()Get the corresponding byte array
Example: String ok= "Apple";
Byte[]bytes=ok.getbytes ();
for (int i=0;i<bytes.length;i++)
System.out.println (bytes );//output byte array with a range of -128---127
(4) indexOf () and LastIndexOf ()
IndexOf () finds the first occurrence of a character or substring.
LastIndexOf () finds the character or substring that is the last occurrence.
(5) substring ()   
It has two forms, the first of which is: String substring (int startIndex)
The second type is: String substring (int startindex,int endIndex)
(6) concat ()Connect two strings
(7) replace ()Replace
It has two forms, the first of which is replaced by a character in the invocation string where all occurrences of a character are in the form:
String replace (char Original,char replacement)
Example: String s= "Hello". Replace (' l ', ' w ');
The second form is to replace another sequence of characters with one character sequence, in the following form:
String replace (charsequence original,charsequence replacement)
(8) trim ()Remove the start and end spaces

(9) valueOf ()Convert to String

(Ten) toLowerCase ()Convert to lowercase

(one) touppercase ()Convert to uppercase
(StartsWith) () and EndsWith ()   
The StartsWith () method determines whether to start with a specific string, and the Endwith () method determines whether to end with a specific string
Please refer to the API of string for more methods
Summary
The String class has immutable (cannot be changed) nature and when a string variable needs to be transformed frequently, it produces many variable values, and should consider using StringBuffer to improve efficiency. At development time, note the method of creating the string. This blog is my own study, if there are errors, hope to amend.


"A string explanation of Java"

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.