Home > Java > javaTutorial > body text

How to use String class, StringBuffer and StringBuilder in Java?

WBOY
Release: 2023-04-21 19:22:19
forward
830 people have browsed it

Basic concepts of the String class

  • The String class is a reference data type, not a basic data type.

  • In Java, as long as it is enclosed in " " (double quotes), it is a String object.

  • Java stipulates that the string in double quotes is immutable, that is to say, "abc" cannot become "abcd" from birth to death, nor can it become "ab".

  • In the JDK, strings enclosed in double quotes are stored in the string constant pool in the method area. (Because in actual development, strings are used very frequently, for the sake of execution efficiency, strings are placed in the string constant pool in the method area)

String characters String storage principle

  • By String s = “abc”, an object will be created in the string constant pool in the method area, and s will save the string in the string constant The address in the pool.

  • Create an object through String s = new String("abc"). First, the "abc" object will be created in the string constant pool (if there is already one in the string constant pool "abc" will not be created again), and then a String class object will be created in the heap area, which will store the address of "abc" in the method area, and s will save the address of the String object in the heap.

Look at the following code:

public class StringTest01 {
    //这两行代码表示创建3个字符串对象,且都在字符串常量池中
    String A = "abc";
    String B = "abc" + "de";
    //通过 new 来创建字符串对象,会先在字符串常量池中寻找"abc"
    //找不到的话就会在字符串常量池中创建一个"abc"对象
    //在堆中创建创建字符串对象,并且保存"abc"在字符串常量池中的地址
    String C = new String("abc");
}
Copy after login

Draw the JVM memory diagram according to the above code as follows:

How to use String class, StringBuffer and StringBuilder in Java?

Know After understanding the storage principle of String class strings, you can easily know the compilation results of the following code:

public class StringTest01 {
    public static void main(String[] args) {
        //没有在堆中创建对象
        //s1与s2都存的是"hello"在字符串常量池中的地址
        String s1 = "hello";
        String s2 = "hello";
        //在堆中创建了对象
        //m,n分别存的是他们在堆中对象的地址
        String m = new String("你好!");
        String n = new String("你好!");
        System.out.println(s1 == s2);//结果为true
        System.out.println(m == n);//结果为false
    }
}
Copy after login

Common construction methods of String class

//String类构造方法的使用
public class StringTest02 {
    public static void main(String[] args) {
        byte []x1 = { 97 , 98 , 99 };
        char []x2 = {'我','是','中','国','人'};
        //String s = new String(byte数组);
        String y1 = new String(x1);
        System.out.println(y1);//ABC
        //String s = new String(byte数组,偏移量,长度)
        String y2  = new String(x1,1,2);
        System.out.println(y2);//BC
        //String s = new String(char数组)
        String y3 = new String(x2);
        System.out.println(y3);//我是中国人
        //String s = new String(char数组,偏移量,长度)
        String y4 = new String(x2,2,3);
        System.out.println(y4);//中国人
    }
}
Copy after login

Common methods of String class

public class StringTest03 {
    public static void main(String[] args) {
        //public char charAt(int index)方法
        //返回索引值处的char类型字符
        char s1 = "中国人".charAt(1);
        System.out.println(s1);//国
        //public int compareTo(String anotherString)方法
        //按字典序比较两个字符串
        System.out.println("abc".compareTo("abd"));//负整数
        System.out.println("abc".compareTo("abc"));//0
        System.out.println("abc".compareTo("abb"));//正整数
        //public boolean contains(CharSequence s)方法
        //判断字符串是否包含s
        System.out.println("abcdefg".contains("efg"));//true
        System.out.println("abcdefg".contains("hij"));//false
        //public boolean endsWith(String suffix)方法
        //判断字符串是否以suffix结尾
        System.out.println("abcde".endsWith("cde"));//true
        System.out.println("abcde".endsWith("qwe"));//false
        //public boolean equalsIgnoreCase(String anotherString) 方法
        //判断两个字符串是否相等,忽略大小写
        System.out.println("ABcd".equalsIgnoreCase("abCD"));//true
        //public byte[] getBytes()
        //将字符串转换成byte数组,并返回
        byte [] s2 = "abcdefg".getBytes();
        for (int i = 0; i < s2.length; i++) {
            System.out.print(s2[i] + " ");
        }//97 98 99 100 101 102 103
        //public int indexOf(String str)
        //判断某个子字符串在当前字符串中第一次出现处的索引
        //若子字符串不存在,返回-1
        System.out.println("abcdefghigk".indexOf("hig"));//7
        System.out.println("abc".indexOf("fgh"));//-1
        //public int lastIndexOf(String str)
        //判断某个子字符串最后一次出现在当前字符串中的索引
        System.out.println("abcdhdhdabc".lastIndexOf("abc"));//8
        //public boolean isEmpty()
        //判断字符串是否为空串
        //底层调用length()方法,空串长度为0
        //注意:判断数组长度是length属性,判断字符串长度是length()方法
        System.out.println("".isEmpty());//true
        //public String replace(char oldChar,char newChar)
        //返回一个将原字符串中所有的oldChar替换为newChar的新字符串,不改变原字符串
        String s3 = "aaatttooo";
        System.out.println( s3.replace(&#39;t&#39;,&#39;q&#39;));//aaaqqqooo
        //public String replace(CharSequence target,CharSequence replacement)
        //CharSequence可以看出String
        //将原字符串中的 target 全部换成 replacement
        String s4 = "abcsgdjsssjabcjdjjdjabc";
        System.out.println(s4.replace("abc","www"));//wwwsgdjsssjwwwjdjjdjwww
        //public String[] split(String regex)
        //以regex为分界线,将字符串分割保存在一个字符串数组当中,并返回
        String s5 = "2022-3-19";
        String [] str = s5.split("-");
        System.out.println(str[0] + str[1] + str[2]);//2022319
        //public String substring(int beginIndex)
        //返回一个以索引beginIndex开始直至结尾的字符串
        System.out.println("abcdefgh".substring(4));//efgh
        //public String substring(int beginIndex,int endIndex)
        //返回一个以索引值beginIndex开始,以索引值endIndex结束(不包含该索引值处的字符)的子字符串
        System.out.println("abcdefgh".substring(2,5));//cde
        //public char[] toCharArray()
        //将一个字符串以字符数组的形式返回
        char[] str2 = "abcdefg".toCharArray();
        for(int i = 0 ; i < str2.length ; i++){
            System.out.println(str2[i]);
        }
        //public String toLowerCase()
        //返回一个将原字符串中所有字符变成小写的新字符串
        System.out.println("ABcDeFG".toLowerCase());//abcdefg
        //public String toUpperCase()
        //返回一个将原字符串中所有字符变成大写的新字符串
        System.out.println("aCbcdEfg".toUpperCase());//ABCDEFG
        //public String trim()
        // 返回一个去除字符串的前后空白(空格)的新字符串
        System.out.println("       abcdefg      ".trim());//abcdefg
        //public static String valueOf(参数列表)
        //参数列表可以是int型,char型,int数组,对象 等等.......
        //String类中唯一一个静态方法,可以直接调用
        //将非字符串转换为字符串
        //println()底层调用的就是valueOf()方法,只要是打印在控制台上的都是字符串
        System.out.println(String.valueOf(true));
    }
}
Copy after login

StringBuffer class

Thinking:

  • What are the effects of frequent use of string splicing?

  • Strings in Java are immutable, and a new string will be generated every time they are spliced.

  • Strings are string constants. In the pool, frequent use of string splicing will occupy a lot of method area space

In order to avoid the above problems, we can use the StringBuffer class

//java.lang.StringBuffer
public class StringBufferTest {
    public static void main(String[] args) {
        //创建一个初始化容量为16个 byte[] 数组(字符串缓冲区对象)
        StringBuffer strBuffer = new StringBuffer();
        //拼接字符串调用 append()方法
        //append()方法底层会调用 System.arraycopy()方法,效率较低
        //append()再追加时,如果byte[]满了之后会自动扩容
        strBuffer.append(1);
        strBuffer.append(&#39;q&#39;);
        strBuffer.append(3.14);
        strBuffer.append("abc");
        System.out.println(strBuffer);//1q3.14abc
        //StringBuffer可以进行一定的优化
        //在创建StringBuffer时尽可能可能给定一个合适的初始化容量
        //从而减少底层数组的扩容次数
        //指定初始化容量的字符串缓冲区
        StringBuffer newstrBuffer = new StringBuffer(100);
    }
}
Copy after login

StringBuilder class

Its usage is very similar to StringBuffer, but there are also big differences:

  • The methods in StringBuffer are modified with the synchronized keyword, which means that StringBuffer is used in a multi-threaded compilation environment. It is safe

  • The methods in StringBuilder are not modified with the synchronized keyword, which means that StringBuilder is unsafe in a multi-threaded compilation environment

The above is the detailed content of How to use String class, StringBuffer and StringBuilder in Java?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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