|NO.Z.00032|——————————|BigDataEnd|——|Java&核心类库.V02|——|Java.v02|StringBuilder类|常用构造方法|
一、StringBuilder类的常用构造方法
| 方法声明 | 功能介绍 |
| StringBuilder() | 使用无参方式构造对象,容量为16 |
| StringBuilder(int capacity) | 根据参数指定的容量来构造对象,容量为参数指定大小 |
| StringBuilder(String str) | 根据参数指定的字符串来构造对象,容量为:16+字符串长度 |
二、编程代码
package com.yanqi.task13;
public class StringBuilderTest {
public static void main(String[] args) {
// 1.使用无参方式构造StringBuilder类型的对象并打印容量和长度
StringBuilder sb1 = new StringBuilder();
System.out.println("sb1 = " + sb1); // 自动调用toString方法 啥也没有
System.out.println("容量是:" + sb1.capacity()); // 16
System.out.println("长度是:" + sb1.length()); // 0
System.out.println("-----------------------------------------------------------");
// 2.使用参数指定的容量来构造对象并打印容量和长度
StringBuilder sb2 = new StringBuilder(20);
System.out.println("sb2 = " + sb2); // 自动调用toString方法 啥也没有
System.out.println("容量是:" + sb2.capacity()); // 20
System.out.println("长度是:" + sb2.length()); // 0
System.out.println("-----------------------------------------------------------");
// 3.根据参数指定的字符串内容来构造对象并打印容量和长度
StringBuilder sb3 = new StringBuilder("hello");
System.out.println("sb3 = " + sb3); // 自动调用toString方法 hello
System.out.println("容量是:" + sb3.capacity()); // 16 + 5 = 21
System.out.println("长度是:" + sb3.length()); // 5
System.out.println("-----------------------------------------------------------");
}
}
三、编译打印
D:\JAVA\jdk-11.0.2\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=54806:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath E:\NO.Z.10000——javaproject\NO.H.00001.javase\javase\out\production\javase com.yanqi.task13.StringBuilderTest
sb1 =
容量是:16
长度是:0
-----------------------------------------------------------
sb2 =
容量是:20
长度是:0
-----------------------------------------------------------
sb3 = hello
容量是:21
长度是:5
-----------------------------------------------------------
Process finished with exit code 0
Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
——W.S.Landor
浙公网安备 33010602011771号