|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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通