创建字符串的几种方法:
1. 直接赋值
String s="HelloWord";
2. 使用构造方法
2.1 根据传入的字符串创建字符串对象
String s=new String("HelloWord");
2.2 根据字符数组创建字符串对象
char[] value = {'a','b','c','d','e'};
String str = new String(value);//s="abcde"
2.3 根据字节数组创建字符串对象
byte[] bytes={97,98,99,100,101};
String s=new String(bytes);//s="abcde"
使用直接赋值法和使用构造方法创建的对象的区别:
使用直接赋值法创建字符串在字符串常量池中存储对象。
使用构造方法创建的对象若常量池中没有对象,即会在常量池中创建对象又会在堆中创建一个对象堆中存放的是常量池中对象的地址。
字符串类用于比较的方法:
==与equals方法的区别
==:对基本数据类型比较的是值,对引用数据类型比较的是地址
equals方法:只能用于引用数据类型的比较,默认比较的是地址,可以对equals进行重写,使其比较的是值,例如String中的equals方法进行了重写。
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String)anObject;
if (coder() == aString.coder()) {
return isLatin1() ? StringLatin1.equals(value, aString.value)
: StringUTF16.equals(value, aString.value);
}
}
return false;
}
练习:
String s1="abc";
String s2="abc";
String s3=new String("abc");
System.out.println(s1==s2);//true
System.out.println(s1==s3);//false
System.out.println(s1.equals(s1));//true
System.out.println(s1.equals(s3));//true
字符串转换成数组的方法
-
char[] toCharArray () :将字符串转换为字符数组
-
byte[] getBytes(): 将字符串转换为字节数组
-
String[] split(String regex) :按照指定字符串进行切割
其他常用的方法
- public char chatAt (int index) 根据索引找字符
- public int length() :返回字符串的长度
- public String substring(int beginIndex) 截取到末尾
- public String substring(int beginIndex, int endIndex) 根据开始和结束索引做截取,包含头不包含尾
- public String replace(旧值,新值) 将旧值替换为新值
- public int indexOf(Stringstr): 返回指定子字符串第一次出现在该字符串内的索引。
基本数据类型转换为字符串的方法:
1.使用拼接空字符串的形式
int x=2;
String s=x+"";
System.out.println(s);//2
2.使用String中静态的valueOf方法
int x=2;
String s=String.valueOf(x);
System.out.println(s);//2