String类又称作不可变字符序列。
String位于java.lang包中,Java程序默认导入java.lang包下的所有类。
String类不能被继承(final)
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence {
...
}
String类用来表示字符串,或则叫字符序列(即一个数组)
char value[] 前面的final意味着它是不可变的,只能被初始化一次
/** The value is used for character storage. */
private final char value[];
Java默认的就是Unicode字符集,Java字符串就是Unicode字符序列,例如字符串“Java”就是4个Unicode字符’J’、’a’、’v’、’a’组成的。
当"+"运算符两侧的操作数中只要有一个是字符串(String)类型,系统会自动将另一个操作数转换为字符串然后再进行连接:
public class Test{
public static void main(String[] args) {
String str = "abc";
String str2 = new String("def");
String str3 = "abc" + "defg";
String str4 = "18" + 19;//不是加法,是字符串连接符
System.out.println(str4);
}
}
输出结果:
1819
字符串常量会被放到常量池里面。
像 "gaoqi" 、 "abc" + "defg"(编译器会自动把它拼接起来,拼接成"abcdefg") 这样的字符串,会自动地放到常量池里面。
public class Test{
public static void main(String[] args) {
String str = "abc";
String str2 = new String("def");
String str3 = "abc" + "defh";
String str4 = "18" + 19;
System.out.println(str4);
System.out.println("############");
String str10 = "gaoqi";
String str11 = "gaoqi";
String str12 = new String("gaoqi");
System.out.println(str10 == str11);
System.out.println(str12 == str11);
}
}
输出结果:
1819
############
true
false
str10和str11都是直接从常量池里面取,所以str10和str11是同一个对象。
str12是新建(new)了一个对象,所以它是一个独立的对象,str12和str11不是同一个对象。
通常比较字符串时,使用equals:
public class Test{
public static void main(String[] args) {
String str1 = "gaoqi";
String str2 = new String("gaoqi");
//通常比较字符串时,使用equals
System.out.println(str2.equals(str1));
}
}
输出结果:
true
String类的equals方法源码:
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}