Home > Java > javaTutorial > body text

A brief introduction to the StringBuilder class in Java

黄舟
Release: 2017-08-13 09:32:14
Original
1543 people have browsed it

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); 
 
  } 
 
}
Copy after login

Running results



hello,java
hellojava
avajolleh
9
16
avajo
Copy after login

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!

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