一、String类的概述
1. String类表示字符串,在java程序中所有双引号的字符串都是String类的对象
2.String类在java.lang包下,所以使用的时候不需要导包
二、创建字符串对象两种方式的区别
1.通过new创建的字符串对象,每一次都会新开辟空间
2.通过""方式直接创建的字符串对象,是常量,在常量池中,只有一份
三、String类的特点
1.String类不可变
2.String类字符串常量对象可以共享
3.String底层是靠字符数组实现的,jdk9底层是字节数组。
四、字符串的比较
1.==号的比较
比较基本数据类型:比较的是具体的值
比较引用数据类型:比较的是内存地址
2. equals方法:字符串是对象,它比较内容是否相同,是通过一个方法来实现的,就是equals()方法
class A{
public static void main(String[]args){
String str=new String("abc");
String srt1=new String("abc");
String str2="abc";
String str3="abc";
//使用equals进行比较并输出
System.out.println(str.equals(srt1));
System.out.println(str2.equals(str3));
}
}
五、String类获取功能的方法
public int length () :返回此字符串的长度。
public String concat (String str) :将指定的字符串连接到该字符串的末尾。
public char charAt (int index) :返回指定索引处的 char值。
public int indexOf (String str) :返回指定子字符串第一次出现在该字符串内的索引。
public String substring (int beginIndex) :返回一个子字符串,从beginIndex开始截取 字符串到字符串结尾。
public String substring (int beginIndex, int endIndex) :返回一个子字符串,从 beginIndex到endIndex截取字符串。含beginIndex,不含endIndex。
public class Test20 {
public static void main(String[] args) {
//length 返还字符串的长度
String str="abcdefg";
int l=str.length();
System.out.println(l);
//concat 将指定的字符串拼接到该字符串后边
String str1="abcdefgh";
String name=str1.concat("shagou");
System.out.println(name);
//charAT 返还该字符串内索引的值
String str2="abcdefghi";
char c=str2.charAt(5);
System.out.println(c);
//index 获取字符在字符串内的的位置
String str3="abcdefghij";
int index=str3.indexOf("d");
System.out.println(index);
//substring 从指定的地方开始截取字符串到末尾
String str4="abcdefjhijka";
String s=str4.substring(4);
System.out.println(s);
//从指定的地方截取到指定的地方
String s1=str4.substring(4,6);
System.out.println(s1);
}
}