使用String对象存储字符串
String s="HelloWord";
String s=
new String();
String s=
new String("HelloWord");
实例:
package com.jredu.ch10;
public class Ch01 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s="HelloWord";
//通过双引号直接创建:在字符串常量池中创建字符串
String s2=s;
//s3创建的内容已经存在,所以再此创建时就会把字符串常量池中的相同字符串s拿出来给s3
String s3="HelloWord";
//字符串常量池中的地址
//通过new关键字创建
String s4=new String("HelloWord");
String s5="Hello";
String s6="Word";
String s7=s5+s6;
String s8="Hello"+"Word";
System.out.println(s==s2);//true
//字符串存储既有基本数据类型的特点,又有引用数据类型的特点
//创建对象:在堆内存中创建对象,在栈内存中形成引用
System.out.println(s==s3);//true
//通过new关键字创建:跟普通对象的创建方式一样
System.out.println(s==s4);//false
System.out.println(s==s7);//false
System.out.println(s==s8);//true
}
}
String类位于java.lang包中,具有丰富的方法:
计算字符串的长度,比较字符串,连接字符串,提取字符串
String类提供了length()方法,确定字符串的长度。
String类提供了equals()方法,比较存储在两个字符串对象的内容是否完全一致(每一个相对应的字符)
equals方法的比较原理:
==和equals的区别:
==判断两个字符在内存中的首地址,即判断是否是同一个字符串
equals()比较存储在两个字符串对象的内容是否完全一致(每一个相对应的字符)
StringBuffer:String增强版 StringBuffer声明
实例:
package com.jredu.ch10;
public class Ch04 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String string="abc";
String string2="123";
String string3=string+string2;
System.out.println(string3);
//结果:abc123
//字符串替换
string3=string3.replace("a", "cf");
System.out.println(string3);
//结果:cfbc123
//推荐使用,出于对内存的优化考虑
StringBuffer stringBuffer=new StringBuffer();
//String str=null;
//追加
//效果犹如:str+="abc";
stringBuffer.append("abc");
//等同于:str+="123";
stringBuffer.append("123");
//插入 5为插入位置的下标
stringBuffer.insert(5, "110");
System.out.println(stringBuffer);
//结果:abc121103
}
}