PRELOADER

当前文章 : 《String比较大全》

5/5/2019 —— 

不同创建方式比较

1
2
3
4
String str1 = "abcd";
String str2 = new String("abcd");
System.out.println(str1==str2);//false
第一种方式是在常量池中拿对象,第二种方式是直接在堆内存空间创建一个新的对象

连接表达式 +

  • 只有使用引号包含文本的方式创建的String对象之间使用“+”连接产生的新对象才会被加入字符串池中。
  • 对于所有包含new方式新建对象(包括null)的“+”连接表达式,它所产生的新对象都不会被加入字符串池中。
1
2
3
4
5
6
7
8
9
String str1 = "str";
String str2 = "ing";

String str3 = "str" + "ing";
String str4 = str1 + str2;
System.out.println(str3 == str4);//false

String str5 = "string";
System.out.println(str3 == str5);//true

字符串的拼接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public static final String A = "ab"; // 常量A
public static final String B = "cd"; // 常量B
public static void main(String[] args) {
String s = A + B; // 将两个常量用+连接对s进行初始化
String t = "abcd";
if (s == t) {
System.out.println("s等于t,它们是同一个对象");
} else {
System.out.println("s不等于t,它们不是同一个对象");
}
}

s等于t,它们是同一个对象,A和B都是常量,值是固定的,因此s的值也是固定的,
它在类被编译时就已经确定了。也就是说:String s=A+B; 等同于:String s="ab"+"cd";

public static final String A; // 常量A
public static final String B; // 常量B
static {
A = "ab";
B = "cd";
}
public static void main(String[] args) {
// 将两个常量用+连接对s进行初始化
String s = A + B;
String t = "abcd";
if (s == t) {
System.out.println("s等于t,它们是同一个对象");
} else {
System.out.println("s不等于t,它们不是同一个对象");
}
}
s不等于t,它们不是同一个对象,A和B虽然被定义为常量,但是它们都没有马上被赋值。
在运算出s的值之前,他们何时被赋值,以及被赋予什么样的值,都是个变数。
因此A和B在被赋值之前,性质类似于一个变量。
那么s就不能在编译期被确定,而只能在运行时被创建了。