Home > Java > javaTutorial > body text

Example introduction to detailed explanation of Java strings

黄舟
Release: 2016-12-19 14:20:51
Original
1339 people have browsed it

1. Create objects

For direct string constants in Java programs, the JVM will use a string pool to save them. When a string direct constant is used for the first time, the JVM will put it into the string pool for caching. Under normal circumstances, string objects in the string pool will not be garbage collected. When the program needs to use the string again, the reference variable can directly point to the existing string in the string without re-creating a new string. The string object created using the new operation does not point to the object in the string pool, but you can use the intern() method to point it to the object in the string pool.

public class StringDemo1 {
     public static void main(String[] args){
         String str1 ="abc";
         String str2 ="abc";
         String str3 =new String("abc");
         System.out.println(str1==str2);//true
         System.out.println(str1==str3);//false
         }
 }
Copy after login

FAQ

String str3 =new String("abc");
Copy after login

How many objects are created?
Answer: How many objects have been created by two

String str ="ab"+"cd";
Copy after login

?


Answer: One. "ab" and "cd" are constants placed in the string pool. Therefore, only one abcd string pool is created and the string abcd is saved in the string pool.

public class StringDemo1 {
    public static void main(String[] args){
        String str1 ="ab";
        String str2 ="cd";
        String str3 ="ab"+"cd";//创建对象并加入字符串池
        String str4 =str1+str2;
        String str5 =str1+"cd";
        System.out.println(str3==str4);//false
        System.out.println(str3==str5);//false

        }
}
Copy after login

It can be seen from the above code: Only String objects created with quotation marks containing text can be added to the string pool. For "+" connection expressions containing new objects created by the new method, the new objects generated by them will not be added. into the string pool.


But there is a situation that needs our attention:

public class StringDemo1 {
    private final static String str1 ="ab";
    private final static String str2 ="cd";
    public static void main(String[] args){
        String str3 ="ab"+"cd";//创建对象并加入字符串池
        String str4 =str1+str2;
        String str5 =str1+"cd";
        System.out.println(str3==str4);//true
        System.out.println(str3==str5);//true

        }
}
Copy after login

Why is this? The reason is this, for constants. Its value is fixed and therefore can be determined at compile time.


Slightly change the above code and see what happens.

public class StringDemo1 {
     private final static String str1 ;
     private final static String str2;
     static{
     str1="ab";
     str2="cd";
     }
     public static void main(String[] args){
         String str3 ="ab"+"cd";//创建对象并加入字符串池
         String str4 =str1+str2;
         String str5 =str1+"cd";
         System.out.println(str3==str4);//false
         System.out.println(str3==str5);//false

         }
 }
Copy after login

Although str1 and str2 are defined as constants, they are assigned values ​​immediately. Before the value of s is calculated, when they are assigned and what value they are assigned are variables, so their properties are the same as variables. Can only be created at runtime.


2. String method

Getting method

•int length()
•char charAt(int index) gets a character based on the position
•int indexOf(int ch) returns ch in the string The position of the first occurrence in
•int indexOf(int ch,int fromIndex) Starting from the position specified by fromIndex, get the position of the first occurrence of ch in the string
•int indexOf(String str)
•int indexOf(String str,int fromIndex)
•int lastIndexOf(int ch)

Judgment method

•boolean contains(String str) Another judgment method: if(str.index(str)!=-1)
•boolean startsWith( String str)
•boolean endsWith(String str)
•bolean isEmpty(String str)
•boolean equals(String str)
•boolean equalsIgnoreCase(String str);

Conversion method

•Convert character array to string

Constructor

1.String(char[] chs)

2.String(char[] chs, offset, count) converts part of the character array into a string.

Static method

1.static String copyValueOf(char[] chs)

2.static String copyValueOf(char[] chs,int offset,int count)

3.static String valueOf(char[] )

4.static String valueOf(char[] chs,int offset,int count)

•Convert a string to a character array

char[] toCharArray

•Convert a character array to a string
•Convert a string to Byte array
byte[] toBytes

Replacement method

String replace(olderStr,newStr)

Cut method

String split(regex)

Get substring [Edit Category]

String subString(begin)

String subString (begin, end) includes the head but not the tail

Convert the string to upper and lower case Android (10)

String toUpperCase()

String toLowerCase()

Remove the spaces at both ends of the string

String trim ()

Compare two strings in natural order

int compareTo(String str)

3.String practice

1. String flipping

public class StringDemo2 {
     public static void main(String[] args){
         String str = "avdkfasjks";
         reverseMethod_1(str);
     }
     public static void reverseMethod_1(String str){
         for(int i=str.length();i>0;i--){
             System.out.print(str.charAt(i-1));
         }
     }
 }
Copy after login

2. Get the largest identical substring

public class StringDemo2 {
    public static void main(String[] args){
        String str1 = "avdkfasjks";
        String str2 = "ewavdrtte";
        System.out.println(commonMaxSubstring(str1, str2));
    }
    public static String commonMaxSubstring(String str1,String str2){
        int len = str1.length();
        String str3 = null;
        outer:
            //i为子串的长度
            for(int i = len;i>0;i--){
                //j为子串的脚标
                for(int j=0;j<len-i+1;j++){
                    str3=str1.substring(j,j+i);
                    if(str2.contains(str3))
                        break outer;

                }
            }
        return str3;
    }
}
Copy after login

That’s it Examples of detailed explanations of Java strings are introduced. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!