Home >Java >javaTutorial >A brief introduction to the StringBuilder class in Java

A brief introduction to the StringBuilder class in Java

黄舟
黄舟Original
2017-08-13 09:32:141559browse

This article mainly introduces the detailed explanation and simple examples of the java StringBuilder class, and implements operations such as appending, inserting, replacing, and deleting the StringBuilder class. Friends in need can refer to it

java Detailed explanation and simple example of StringBuilder class

Implementation code:


##

public class StringBuilderTest { 
 
  /** 
   * @param args 
   */ 
  public static void main(String[] args) { 
    StringBuilder sb = new StringBuilder(); 
    // 追加字符串 
    sb.append("java");//sb = "java" 
    // 插入 
    sb.insert(0 , "hello "); // sb="hello java" 
    // 替换 
    sb.replace(5, 6, ","); // sb="hello,java" 
    System.out.println(sb); 
    // 删除 
    sb.delete(5, 6); // sb="hellojava" 
    System.out.println(sb); 
    // 反转 
    sb.reverse(); // sb="avajolleh" 
    System.out.println(sb); 
    System.out.println(sb.length()); // 输出9 
    System.out.println(sb.capacity()); // 输出16 
    // 改变StringBuilder的长度,将只保留前面部分 
    sb.setLength(5); // sb="avajo" 
    System.out.println(sb); 
 
  } 
 
}

Running results



hello,java
hellojava
avajolleh
9
16
avajo

Code description

The above code demonstrates the append, insert, replace, delete and other operations of the StringBuilder class. These operations change the characters in the StringBuilder Sequence, this is the biggest difference between StringBuilder and String: StringBuilder's character sequence is variable. From the program, we can see that the length() method of StringBuilder returns the length of its character sequence, and the return value of capacity() is greater than the return value of length().

The above is the detailed content of A brief introduction to the StringBuilder class in Java. For more information, please follow other related articles on the PHP Chinese website!

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