- String类
- 概述
- String 对象的创建
- 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() {
// 通过字面量定义的方式:此时的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() {
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
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"));//返回第一次出现的索引
}



