创建String字符串的三种方式:
- 使用new关键字创建
String s1 = new String("abc");
- 直接创建
String s2 = "abc";
- 使用字符串连接创建
String s3 = "ab" + "c";
String字符串的特性:
- 1、在创建的时候会在堆内存的String池中查看该字符串是否存在,如果不存在,则使用new关键字创建一个,如果存在,则无需重新创建。
- 2、只有使用new关键字创建一定会在内存中重新创建一个对象
String字符串中两个字符串使用“==”与equals方法区别
- 当两个字符串使用“==”进行比较时,比较的是两个字符串在内存中的地址
- 当两个字符串使用equals方法比较时,比较的是两个字符串的值
String s1 = "abc";
String s2 = "abc";
String s3 = new String("abc");
String s4 = new String("abc");
System.out.println((s1 == s2) + " and " + (s1.equals(s2)));
System.out.println((s1 == s3) + " and " + (s1.equals(s3)));
System.out.println((s3 == s4) + " and " + (s3.equals(s4)));
true and true
false and true
true and true
String字符串一些情况下的“==”比较
String s1 = "abc";
String s2 = "abc";
System.out.println("The result: " + (s1 == s2));
The result: true
String s1 = "abc";
String s2 = "ab" + "c";
System.out.println("The result: " + (s1 == s2));
The result: true
- 当使用编译期间可以确定结果的变量表达式创建字符串时
final String s1 = "c";
String s2 = "abc";
String s3 = "ab" + s1;
System.out.println("The result: " + (s2 == s3));
The result: true
String s1 = "c";
String s2 = "abc";
String s3 = "ab" + s1;
final String s4 = getString();
String s5 = "ab" + s4;
System.out.println("The result: " + (s2 == s3));
System.out.println("The result: " + (s2 == s5));
public String getString(){
return "c";
}
The result: false
The result: false
以上代码中,s1不是final类型的,所以只有在代码运行时值才能确定,s4虽然定义成final类型的,但是其值是通过getString这个方法得来的,其值也只能在代码运行才能确定。