String类是一种引用数据类型,且字符串在创建后不能被修改,如果改变对象内容,改变的知识被引用的指向。
String str1 = "Hello";
String str2 = new String("Hello");
char[] arr = {'H','e','l','l','o'};
String str3 = new String(arr);
字符串的比较
==:如果比较的是基本数据类型,则比较的是数值是否相等;如果比较的是应用数据类型,则比较的是对象的地址值是否相等。
equals:用来比较两个对象的内容是否相等。(不能用于比较基本数据类型)。如果没有对equals方法进行重写,则比较的是引用类型的变量所指向的地址(很多类重写了equals方法,比如String,Integer等把它变成了值比较,所以一般情况下equals都是比较值是否相等)。
我们分析创建字符串不同的方式,演示代码如下:
import java.lang.String;
public class StringDemo1 {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = new String("hello");
String s5 = s1;
if (s1 == s2) {
System.out.println("s1 == s2");
} else if (s1.equals(s2)) {
System.out.println("s1.equals(s2)");
}
if (s3 == s4) {
System.out.println("s3 == s4");
} else if (s1.equals(s2)) {
System.out.println("s3.equals(s4)");
}
if (s1 == s3) {
System.out.println("s1 == s3");
} else if (s1.equals(s2)) {
System.out.println("s1.equals(s3)");
}
if (s1 == s5) {
System.out.println("s1 == s5");
} else if (s1.equals(s2)) {
System.out.println("s1.equals(s5)");
}
}
}
执行结果:
s1 == s2 s3.equals(s4) s1.equals(s3) s1 == s5
String 创建的字符串存储在公共池中,而 new 创建的字符串对象在堆上
常用方法
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 StringDemo2 {
public static void main(String[] args) {
//创建字符串对象
String s = "hello";
//int length():获取字符串的长度,其实也就是字符个数
System.out.println(s.length());
System.out.println("‐‐‐‐‐‐‐‐");
// String concat (String str):将将指定的字符串连接到该字符串的末尾.
String s2 = s.concat(" world");
System.out.println(s2);
// char charAt(int index):获取指定索引处的字符
System.out.println(s.charAt(0));
System.out.println(s.charAt(1));
System.out.println("‐‐‐‐‐‐‐‐");
// int indexOf(String str):获取str在字符串对象中第一次出现的索引,没有返回‐1
System.out.println(s.indexOf("l"));
System.out.println("‐‐‐‐‐‐‐‐");
// String substring(int start):从start开始截取字符串到字符串结尾
System.out.println(s.substring(0));
System.out.println(s.substring(3));
System.out.println("‐‐‐‐‐‐‐‐");
// String substring(int start,int end):从start到end截取字符串。含start,不含end。
System.out.println(s.substring(0, s.length()));
System.out.println(s.substring(1, 4));
}
}
执行结果:
5
‐‐‐‐‐‐‐‐
hello world
h
e
‐‐‐‐‐‐‐‐
2
‐‐‐‐‐‐‐‐
hello
lo
‐‐‐‐‐‐‐‐
hello
ell
StringBuffer与StringBuilder
由于String不可修改,所以出现了StringBuffer与StringBuilder类,对其进行修改时不会产生新的未使用对象,适用于需要频繁修改字符串的情况使用,StringBuffer与StringBuilder大部分功能相同。
StringBuffffer采用同步处理,属于线程安全操作;而StringBuilder未采用同步处理,属于线程不安全操作。



