对于字符串 string, 因为广泛使用,JVM为了提高效率,节省内存,如果两个字符串字面值相同,这两个string变量共享唯一一个实例, 这样的实例叫做限定字符串(interned string)
String s1 = "Welcome to Java"; // 限定字符串
String s2 = new String("Welcome to Java");
String s3 = "Welcome to Java"; // 同 s1,限定字符串
System.out.println("s1 == s2 is " + (s1 == s2));
System.out.println("s1 == s3 is " + (s1 == s3));
System.out.println("s1.equals(s2) is " + s1.equals(s2));
System.out.println("s1.equals(s3) is " + s1.equals(s3));
输出:
s1 == s2 is false
s1 == s3 is true
s1.equals(s2) is true
s1.equals(s3) is true
字符串的替换和分割:
"Welcome".replace('e', 'A')
returns a new string, WAlcomA
.
"Welcome".replaceFirst("e", "AB")
returns a new string, WABlcome
.
"Welcome".replace("e", "AB")
returns a new string, WABlcomAB
.
"Welcome".replace("el", "AB")
returns a new string, WABcome
.
String[] tokens = "Java#HTML#Perl".split("#");
for (int i = 0; i < tokens.length; i++)
System.out.print(tokens[i] + " ");
显示:Java HTML Perl
重载的构造函数,参数少的可以调用参数多的,使用this
关键字:
public BMI(String name, int age, double weight, double height) {
this.name = name;
this.age = age;
this.weight = weight;
this.height = height;
}
public BMI(String name, double weight, double height) {
this(name, 20, weight, height); // 调用上一个构造函数
}
和数据域相关的方法: getter (or accessor), setter (or mutator)