StringBuffer(字符串缓冲区)
StringBuffer是线程安全的 可变的序列
程序会给StringBuffer一个默认的容量(理论值)—->16
但当你往StringBuffer中加入更多的东西时 程序又会自动帮StringBuffer添加容量 所以StringBuffer是一个可变的序列
如何往StringBuffer中添加字符或者字符串呢?
添加—>append(默认从最后一个字符开始添加)
StringBuffer sb = new StrigBuffer();
sb.append("helloworld");
System.out.println(sb);
输出
helloworld
这样我们就往一个空的StringBuffer中添加了helloworld
插入—>insert
Stringbuffer sb = new StringBuffer();
sb.append("helloworld");
sb.insert(5,"znb");
System.out.println(sb);
输出
helloznbworld
这样就在helloworld
的第五个下标开始插入了znb
删除—>delete/deleteCharAt
Stringbuffer sb = new StringBuffer();
sb.append("helloworld");
sb.delete(0,5);
System.out.println(sb);
输出
world
从下标为0到下标为4的字符就被删除掉了
注意: 删除是留头不留尾–>首下标会被删除 但后面的下标会往前推一个删除(至于为什么 你还是问高林斯吧)
单个字符删除
Stringbuffer sb = new StringBuffer();
sb.append("helloworld");
sb.deleteCharAt(4);
System.out.println(sb);
输出
hellworld
下标为4的字符被删除
替换—>replace/setCharAt
Stringbuffer sb = new StringBuffer();
sb.append("helloworld");
sb.replace(3,5,"znb");
System.out.println(sb);
输出
helznbworld
从下标为3到5之间的字符串被替换成znb
单个字符删除
Stringbuffer sb = new StringBuffer();
sb.append("helloworld");
sb.setCharAt(4,z);
System.out.println(sb);
输出
hellzworld
把下标为4的字符替换成了z
反转—>reverse
Stringbuffer sb = new StringBuffer();
sb.append("helloworld");
sb.reverse();
System.out.println(sb);
输出
dlrowolleh
整个字符串反转过来
权限修饰符
我们现在学习到的权限修饰符有4种
分别是
public —>公开的
protected—>受保护的
default—>默认的(不添加修饰符)
private—>私有的
本类 同包类 同包子类 不同包子类 不同包类
public ✅ ✅ ✅ ✅ ✅
protected ✅ ✅ ✅ ✅ ❌
default ✅ ✅ ✅ ❌ ❌
private ✅ ❌ ❌ ❌ ❌
可以看到这些修饰符在不同的类的不同权限
包装类
我们到现在已经学过不少的基本数据类型
那么这些基本数据类型都是可以封装成一个类的
封装成一个类 类中就可以写成员方法了
一起来看一下
int Integer
short Short
long Long
byte Byte
double Double
float Float
char Character
boolean Boolean
可以看到这些基本数据类型除了int与char类型的包装类有些不同之外 其他的数据类型都只是把首字母换成了大写而已 所以我们主要记一下int与char的包装类就可以了
int的包装类Integer
Integer有自动装箱和自动拆箱功能
Integer num = 10; //装箱
int num2 = num + 3;//拆箱
装箱: 用Integer直接声明一个int类型的数 系统会自动把这个int类型的数转换成Integer类型
拆箱: 在int类型的赋值计算时碰到Integer 系统会帮你自动把Integer类型转换成int类型
注意: 在拆箱中 Integer类型的值不能为null 因为null是不能转换成int类型的
进制转换—>toBinaryString/toOctalString/toHexString
分别是十进制转换成二进制/八进制/十六进制
System.out.println(Integer.toBinaryString(250));
System.out.println(Integer.toOctalString(250));
System.out.println(Integer.toHexString(250));
输出
11111010
372
fa
分别打印出了250的二进制/八进制/十六进制
利用字符串来创建 Integer对象(只能是数字字符串)
Integer in = new Integer("250");
System.out.println(in);
输出
250