知识库 知识库
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)

Jim FuckPPT

Java小学生
首页
  • Hyperskill - Java

    • Java basic
    • Java OOP
    • 应知
    • 扩展
    • IO & Stream
    • Error & Exception
    • Algorithm & Data structure
    • Design pattern
    • Web
    • Spring boot
  • 练习题

    • 选择题 & 填空题
    • 代码题
  • Frank - Java与生活 (OOP)

    • 参考资料
    • Java基础
    • OOP上半部分
    • OOP下半部分
  • Frank - Java API进阶

    • Base API
    • Unit Test and main function
  • 学习笔记
  • 学习笔记

    • 数据库
  • Frank - MySQL删库跑路

    • 安装、连接、配置
    • 基本操作——数据库
    • 基本操作——表
    • 基本操作——数据
    • 数据类型
    • 列属性完整性
    • 数据库设计思维
    • 单表查询
    • 多表查询
  • 学习笔记

    • 其它
  • Frank - Linux现代方法

    • 必知
    • 命令
    • 技巧
  • 技术文档
  • Git
  • GitHub技巧
  • 前端
  • Khan Academy - 语法
  • Monthly
  • 阅读
  • Others
  • 学习
  • 面试
  • 心情杂货
  • 实用技巧
  • 友情链接
收藏
  • 标签
  • 归档
GitHub (opens new window)
  • Hyperskill - Java

    • Java basic

    • Java OOP

    • 应知

      • Theory:Functional decomposition
      • Theory:Paradigms
      • Theory:Overloading
      • Theory:Write, compile, and run
      • Theory:Annotations basics
      • Theory:JVM, JRE, and JDK
      • Theory:Jave Archive
      • Theory:Running programs on your computer
      • Theory:Enums in Java
      • Theory:Fields and methods in enum
      • Theory:StringBuilder
        • Mutable strings
        • Constructing objects
        • Some important methods
        • The length() and capacity()
        • Conclusion
      • Theory:Immutability
      • Theory:Boxing and unboxing
      • Theory:Introduction to generic programming
      • Theory:Generics and Object
      • Theory:What are collections
      • Theory:The collections Framework overview
      • Theory:ArrayList
      • Theory:The List interface
      • Theory:Comparable
      • Theory:Processing strings
      • Theory:Initialization blocks
      • Theory:Introduction to API
      • Theory:Generic methods
    • 扩展

    • IO & Stream

    • Error & Exception

    • Algorithm & Data structure

    • Design pattern

    • Web

    • Spring boot

  • 练习题

  • Frank - Java与生活

  • Frank - Java API进阶

  • 学习笔记

  • Java
  • Hyperskill - Java
  • 应知
Jim
2022-09-15
目录

Theory:StringBuilder

# Mutable strings

As you may know, strings in Java are immutable. It means that once created, a string cannot be changed. If we want to modify the content of a string object, we should create a new string. This may not be the best way when we perform a lot of modifications because each operation creates a new object, which is bad for performance.

Fortunately, there is a special class named StringBuilder that is used to create mutable string objects. An object of this class is similar to a regular string, except that it can be modified. As an example, it is better to use StringBuilder than String where lots of concatenations are performed at runtime.

# Constructing objects

It is possible to create an empty object of the type StringBuilder:

StringBuilder empty = new StringBuilder();
System.out.println(empty); // ""
1
2

or pass a string to it:

StringBuilder sb = new StringBuilder("Hello!");
System.out.println(sb); // "Hello!"
1
2

提示

Note, we do not need to import anything to use this class in programs.

# Some important methods

The StringBuilder class provides a set of useful methods to manipulate objects. Let's consider some of them.

  • int **length**() returns the length (the character count), like in regular strings. This method does not modify the object.
StringBuilder sb = new StringBuilder("I use Java");
System.out.println(sb.length()); // 10
1
2
  • char **charAt**(int index) returns a character located at the specified index. The first character has the index 0. This method does not modify the object.
StringBuilder sb = new StringBuilder("I use Java");
System.out.println(sb.charAt(0)); // 'I'
System.out.println(sb.charAt(6)); // 'J'
1
2
3
  • void **setCharAt**(int index, char ch) sets a character located at the specified index to ch.
StringBuilder sb = new StringBuilder("start");
sb.setCharAt(1, 'm');
System.out.println(sb); // "smart"
1
2
3
  • StringBuilder **deleteCharAt**(int index) removes the character at the specified position.
StringBuilder sb = new StringBuilder("dessert");
sb.deleteCharAt(2);
System.out.println(sb); // "desert"
1
2
3
  • StringBuilder **append**(String str) concatenates the given string to the end of the invoking StringBuilder object. There are also several overloadings to take primitive types and even arrays of characters.
StringBuilder sb = new StringBuilder("abc");
sb.append("123");
System.out.println(sb); // "abc123"
1
2
3

It is also possible to invoke this method multiple times on the same object in the same statement because this method returns the same modified object.

StringBuilder messageBuilder = new StringBuilder(); // empty

messageBuilder
        .append("From: Kate@gmail.com\n")
        .append("To: Max@gmail.com\n")
        .append("Text: I lost my keys.\n")
        .append("Please, open the door!");

System.out.println(messageBuilder);
1
2
3
4
5
6
7
8
9

Output:

From: Kate@gmail.com
To: Max@gmail.com
Text: I lost my keys.
Please, open the door!
1
2
3
4
  • StringBuilder **insert**(int offset, String str) inserts the given string into the existing StringBuilder object at the given position indicated by the offset. This method has a lot of overloadings for different types.
StringBuilder sb = new StringBuilder("I'm a programmer.");
sb.insert(6, "Java ");
System.out.println(sb); // I'm a Java programmer.
1
2
3
  • StringBuilder **replace**(int start, int end, String str) replaces the substring from the specified string index (inclusive) to the end index (exclusive) with a given string.
StringBuilder sb = new StringBuilder("Let's use C#");
sb.replace(10,12,"Java");
System.out.println(sb); // Let's use Java
1
2
3
  • StringBuilder **delete**(int start, int end) removes the substring from the start index (inclusive) to the end index (exclusive).
StringBuilder sb = new StringBuilder("Welcome");
sb.delete(0,3);
System.out.println(sb); // "come"
1
2
3
  • StringBuilder **reverse**() causes this character sequence to be replaced by the reverse of the sequence.
StringBuilder sb = new StringBuilder("2 * 3 + 8 * 4");
sb.reverse();
System.out.println(sb); // "4 * 8 + 3 * 2"
1
2
3

提示

Note, when you have a StringBuilder object, you can get a String by invoking the toString method.

For more details about methods see the documentation (opens new window).

# The length() and capacity()

There are two methods that should not be confused: length and capacity. The length returns the actual number of characters whereas capacity returns the amount of storage available for newly inserted characters, beyond which an allocation will occur. The capacity is a part of the internal representation of StringBuilder, and its value will dynamically change.

The following example will help you better distinguish these methods:

StringBuilder sb = new StringBuilder(); // initial capacity is 16

System.out.println(sb.length());   // 0
System.out.println(sb.capacity()); // 16

sb.append("A very long string");

System.out.println(sb.length());   // 18
System.out.println(sb.capacity()); // 34
1
2
3
4
5
6
7
8
9

It is possible to specify the capacity when creating a StringBuilder object, but it is not used very often:

StringBuilder sb = new StringBuilder(30);

System.out.println(sb.length());   // 0
System.out.println(sb.capacity()); // 30
1
2
3
4

# Conclusion

The StringBuilder class is used to create mutable strings, which can be modified at runtime. You can perform different operations on StringBuilder objects, like append, reverse, replace, delete, etc. No new objects will be created. It is recommended to use this class instead of String when a lot of modifications are performed. This will prevent the creation of multiple intermediate objects; therefore, it will work faster and require less memory. One common case for this is a sequence of concatenations.

提示

Note, there is another similar class called StringBuffer. We will consider it in coming topics.

编辑 (opens new window)
#String#Java
上次更新: 2023/02/14, 11:54:58
Theory:Fields and methods in enum
Theory:Immutability

← Theory:Fields and methods in enum Theory:Immutability→

最近更新
01
《挪威的森林》
04-14
02
青钢影
04-14
03
Processing strings
02-18
更多文章>
Theme by Vdoing | Copyright © 2022-2023 Jim Frank | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式