String类
概述
特性:
1)String是一个final类,代表不可变的字符序列
2)用双引号表示,他的值在创建后不能更改
3)String对象的字符内容是存储在一个字符数组value[]中的
String s1="abc";//字面量的定义形式
String s2="abc";
System.out.println(s1==s2);//比较s1和s2的地址值
//返回true
String 对象的创建
public void test2() {
/**
* 实例话方式
* 1. 通过字面量定义的方式
* 2. 通过new+构造器的方式
*/
// 通过字面量定义的方式:此时的s1和s2的数据声明在方法区中的字符串常量池中
String s1 = "hello";
String s2 = "hello";
// 此时的s3和s4保存的地址值,是数据在堆空间中开辟空间以后对应的地址值
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s1 == s2);//true
System.out.println(s1 == s3);//false
System.out.println(s1 == s4);//false
System.out.println(s3 == s4);//false
Person person1=new Person("zhangsan",12);
Person person2=new Person("zhangsan",12);
System.out.println(person1.name.equals(person2.name));
System.out.println(person1.name==person2.name);
}
@Test
public void test3() {
/**
* 常量与常量的拼接结果在常量池.且常量池中不会存在相同内容的常量
* 只要其中有一个是变量,结果就在堆中.
* 如果拼接的结果调用intern()方法,返回值就在常量池中
*/
String s1 = "Javaee";
String s2 = "hadoop";
String s3 = "Javaeehadoop";
String s4 = "Javaee" + "hadoop";
String s5 = s1 + "hadoop";
String s6 = "Javaee" + s2;
String s7 = s1 + s2;
System.out.println(s3 == s4);//true
System.out.println(s3 == s5);//false
System.out.println(s3 == s6);//false
System.out.println(s3 == s7);//false
System.out.println(s5 == s6);//false
System.out.println(s5 == s7);//false
System.out.println(s6 == s7);//false
String s8=s5.intern();
System.out.println(s3 == s8);//true
}
String 方法
@Test
public void test1(){
String s1=" Hello World ";
System.out.println(s1.length());
for(int i=0;i<s1.length();i++){
char s=s1.charAt(i);
System.out.println(s);
}
// System.out.println(s1.charAt(1));
System.out.println(s1.isEmpty());
System.out.println(s1.toLowerCase());//s1不可变
System.out.println(s1.toUpperCase());
System.out.println(s1.trim());//去除首尾多余的空格
String s2="ac";
String s3="ad";
System.out.println(s2.compareTo(s3));//涉及到字符串排序
String s4="涉及到字符串排序";
System.out.println(s4.substring(3, 6));
String s1="helloworld";
boolean b1=s1.endsWith("ld");//测试此字符串是否以指定的后缀结束
System.out.println(b1);
boolean b2=s1.startsWith("ld");//测试此字符串是否以指定的后缀结束
System.out.println(b2);
System.out.println(s1.contains("hell"));
System.out.println(s1.indexOf("o"));//返回第一次出现的索引
}