[Java Basics] String, analyze memory address, source code

Series Article Directory

[Java Basics] StringBuffer and StringBuilder class application and source code analysis
[Java Basics] array application and source code analysis
[Java Basics] String, analyze memory address, source code



foreword

Strings are widely used in Java programming. Strings are objects in Java. Java provides the String class to create and manipulate strings.

1. Create a string

The easiest way to create a string is as follows:

String str = "hello , world!";

When a string constant is encountered in the code, where the value is "hello, world!", the compiler will use this value to create a String object.
Like other objects, you can use keywords and constructors to create String objects.
Create strings with constructors:

String str2=new String("hello , world!");

Strings created by String are stored in the public pool, while string objects created by new are on the heap:

String s1 = "hello , world!"";              // String 直接创建
String s2 = "hello , world!"";              // String 直接创建
String s3 = s1;                    // 相同引用
String s4 = new String("hello , world!"");   // String 对象创建
String s5 = new String("hello , world!"");   // String 对象创建

1.1. Construction method

The String class has 11 construction methods, which provide different parameters to initialize the string, such as providing a character array parameter:

public class StringDemo{
    
    
    public static void main(String args[]){
    
    
        char[] helloArray = {
    
     'h', 'e', 'l', 'l', 'o'};
        String helloString = new String(helloArray);
        System.out.println( helloString );
    }
}

The result of compiling and running the above example is as follows:

hello

1.2. Test the memory address of the String object

The String class is immutable, so once you create a String object, its value cannot be changed.
If you need to do a lot of modifications to the string, then you should choose to use the StringBuffer & StringBuilder class.

1.2.1. Create a tool class, return the class name of the object and the hashcode of the memory identity

public class ObjectCommon {
    
    

    /**
     * 返回 对象的类名称 和 内存身份hashcode
     * @param obj
     * @return
     */
    public static String toString(Object obj) {
    
    
        return obj.getClass().getName() + "@" + Integer.toHexString(System.identityHashCode(obj));
    }

}

1.2.2. Test code

The value of the string s1 has been modified three times, and the memory address pointed to each time is different.

 public static void main(String[] args) {
    
    
       String s1 = "Hello";
        System.out.println(ObjectCommon.toString(s1));
        s1 = " world ";
        System.out.println(ObjectCommon.toString(s1));
        s1 = s1 + " ! ";
        System.out.println(ObjectCommon.toString(s1));
 }

java.lang.String@4554617c
java.lang.String@74a14482
java.lang.String@1540e19d

1.2.3. View the value definition in the source code (based on JDK1.8)

In the String class in JDK1.8, the variable name of the value is value, the type is: char [], and it is added with final, which means that the value cannot be modified. The modification we see points to the memory reference address of the new data object.

public final class String
    implements java.io.Serializable, Comparable<String>, CharSequence {
    
    
    /** The value is used for character storage. */
    private final char value[];
}

2. String length

Methods used to obtain information about an object are called accessor methods.
One of the accessor methods of the String class is the length() method, which returns the number of characters a string object contains.
After the following code is executed, the len variable is equal to 15:

public class StringDemo {
    
    
    public static void main(String args[]) {
    
    
        String site = "www.google.com";
        int len = site.length();
        System.out.println( "google网址长度 : " + len );
    }
}

The result of compiling and running the above example is as follows:

google url length: 13

3. Connection string

The String class provides methods for concatenating two strings, concat and +

3.1、concat

string1.concat(string2);

Returns a new string of string2 concatenated with string1. You can also use the concat() method on string constants, such as:

"我的名字是 ".concat("Google");

3.1、+

It is more common to use the '+' operator to concatenate strings, such as:

"Hello," + " google" + "!"

The result is as follows:

“Hello, google!”

Below is an example:

public class StringDemo {
    
    
    public static void main(String args[]) {
    
    
        String string1 = "google网址:";
        System.out.println("1、" + string1 + "www.google.com");
    }
}

The result of compiling and running the above example is as follows:

1. Google URL: www.google.com

4. Create a formatted string

We know that outputting formatted numbers can use the printf() and format() methods.
The String class uses the static method format() to return a String object instead of a PrintStream object.
The static method format() of the String class can be used to create reusable formatted strings, not just for one printout.

4.1、printf

float floatVar = 10.10f;
        int intVar = 10;
        String stringVar = "10元";

        System.out.printf("浮点型变量的值为 %f, 整型变量的值为 %d, 字符串变量的值为 %s", floatVar, intVar, stringVar);

The result is as follows:

The value of the floating-point variable is 10.100000, the value of the integer variable is 10, and the value of the string variable is 10 yuan

4.2、format

float floatVar = 10.10f;
        int intVar = 10;
        String stringVar = "10元";
        String fs = String.format("浮点型变量的值为 %f, 整型变量的值为 %d, 字符串变量的值为 %s", floatVar, intVar, stringVar);
        System.out.println(fs);

The result is as follows:

The value of the floating-point variable is 10.100000, the value of the integer variable is 10, and the value of the string variable is 10 yuan

5. String method

SN (serial number) method description
1 char charAt(int index) returns the char value at the specified index.
2 int compareTo(Object o) compares this string with another object.
3 int compareTo(String anotherString) compares two strings lexicographically.
4 int compareToIgnoreCase(String str) Compares two strings lexicographically, regardless of case.
5 String concat(String str) concatenates the specified string to the end of this string.
6 boolean contentEquals(StringBuffer sb) Returns true if and only if the string has characters in the same order as the specified StringBuffer.
7 static String copyValueOf(char[] data) Returns the String representing the character sequence in the specified array.
8 static String copyValueOf(char[] data, int offset, int count) returns the String representing the character sequence in the specified array.
9 boolean endsWith(String suffix) Tests whether this string ends with the specified suffix.
10 boolean equals(Object anObject) Compares this string with the specified object.
11 boolean equalsIgnoreCase(String anotherString) compares this String with another String, regardless of case.
12 byte[] getBytes() Encodes this String into a sequence of bytes using the platform's default charset and stores the result in a new byte array.
13 byte[] getBytes(String charsetName) Encode this String into a sequence of bytes using the specified charset and store the result in a new byte array.
14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copies characters from this string to the destination char array.
15 int hashCode() returns the hash code of this string.
16 int indexOf(int ch) returns the index of the first occurrence of the specified character in this string.
17 int indexOf(int ch, int fromIndex) Returns the index of the first occurrence of the specified character in this string, starting the search from the specified index.
18 int indexOf(String str) Returns the index of the first occurrence of the specified substring within this string.
19 int indexOf(String str, int fromIndex) Returns the index of the first occurrence of the specified substring within this string, starting at the specified index.
20 String intern() Returns the canonical representation of a String object.
21 int lastIndexOf(int ch) Returns the index of the last occurrence of the specified character in this string.
22 int lastIndexOf(int ch, int fromIndex) Returns the index of the last occurrence of the specified character in this string, starting the reverse search from the specified index.
23 int lastIndexOf(String str) Returns the index of the rightmost occurrence of the specified substring in this string.
24 int lastIndexOf(String str, int fromIndex) Returns the index of the last occurrence of the specified substring in this string, searching backward from the specified index.
25 int length() Returns the length of this string.
26 boolean matches(String regex) Tells whether this string matches the given regular expression.
27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) Tests whether two string regions are equal.
28 boolean regionMatches(int toffset, String other, int ooffset, int len) Tests whether two string regions are equal.
29 String replace(char oldChar, char newChar) Returns a new string obtained by replacing all occurrences of oldChar in this string with newChar.
30 String replaceAll(String regex, String replacement) Replaces all substrings of this string that match the given regular expression with the given replacement.
31 String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement.
32 String[] split(String regex) Splits this string based on matches of the given regular expression.
33 String[] split(String regex, int limit) Splits this string based on matching the given regular expression.
34 boolean startsWith(String prefix) Tests whether this string starts with the specified prefix.
35 boolean startsWith(String prefix, int toffset) Tests whether a substring of this string starting with the specified index starts with the specified prefix.
36 CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence that is a subsequence of this sequence.
37 String substring(int beginIndex) Returns a new string that is a substring of this string.
38 String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string.
39 char[] toCharArray() 将此字符串转换为一个新的字符数组。
40 String toLowerCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为小写。
41 String toLowerCase(Locale locale) 使用给定 Locale 的规则将此 String 中的所有字符都转换为小写。
42 String toString() 返回此对象本身(它已经是一个字符串!)。
43 String toUpperCase() 使用默认语言环境的规则将此 String 中的所有字符都转换为大写。
44 String toUpperCase(Locale locale) 使用给定 Locale 的规则将此 String 中的所有字符都转换为大写。
45 String trim() 返回字符串的副本,忽略前导空白和尾部空白。
46 static String valueOf(primitive data type x) 返回给定data type类型x参数的字符串表示形式。
47 contains(CharSequence chars) 判断是否包含指定的字符系列。
48 isEmpty() 判断字符串是否为空。

5.1、案例

过滤png后缀的数据,并且把文件名和后缀打印出来


    public static void main(String[] args) {
    
    

        // 过滤png后缀的数据,并且把文件名和后缀打印出来
        String fileName = "D://java/环境安装.docx,D://java//soft//chromedriver/chromedriver.exe,D://java//soft//chromedriver/other.png";

        //用到了字符串分割
        String files[] = fileName.split(",");

        //判断文件类型
        for (String file : files) {
    
    

            //System.out.println( file.contains(".png") );
            //System.out.println( file.indexOf(".png") );

            //用到了endsWith  可替代方法:contains 、indexOf
            if( file.endsWith(".png") ) {
    
    
                //用到了lastIndexOf
                int lastIndex = file.lastIndexOf("/");
                System.out.println(" / 最后的位置:" + lastIndex );

                // 从/最后的位置截取数据
                System.out.println("文件名:" + file.substring(lastIndex+1, file.length()));

                System.out.printf("文件 %s 是图片文件" , file );
            } else {
    
    
                System.out.printf("文件 %s 是未知的格式" , file);
            }
            System.out.println();
            System.out.println("------------------------------------");
            System.out.println();
        }

    }

结果:

文件 D://java/环境安装.docx 是未知的格式
------------------------------------

文件 D://java//soft//chromedriver/chromedriver.exe 是未知的格式
------------------------------------

 / 最后的位置:28
文件名:other.png
文件 D://java//soft//chromedriver/other.png 是图片文件
------------------------------------

Guess you like

Origin blog.csdn.net/s445320/article/details/131562073