您的位置:首页 > 编程语言 > Java开发

Java-字符串问题

2016-03-01 10:16 330 查看
String具有不变性。
当两个字符串都是这样声明的时候,其实这里面它们指向的是同一个内存地址。

String s1 = "hello";

String s2 = "hello";

可以通过下面的两个例子做比较:

例1:

public class StringTestTwo {
public static void main(String[] args){
String str1 = "hello";
String str2 = "hello";
System.out.println(str1.equals(str2));
System.out.println(str1==str2);
}
}

打印输出的结果为:
true
true

例2:

public class StringTestTwo {
public static void main(String[] args){
String str1 = new String("hello");
String str2 = new String("hello");
System.out.println(str1.equals(str2)); //equals 判断两个字符串的内容是否一致
System.out.println(str1==str2); //判断两个字符串的地址是否一致,如果地址一致了那么内容肯定一致
}
}

打印结果为:
true
false

通过这两个例子就应该知道其中的要点了。
还有就是注意,StringBuffer类中的append()方法的使用,请与String类中的concat()方法进行比较。

例1:

public class StringTestTwo {
public static void main(String[] args){

StringBuffer stbu = new StringBuffer("Hello,");
stbu.append("teacher!");
stbu.append(" My name is wangjinghsuai!");
System.out.println(stbu);

}
}

打印的结果为:
Hello,teacher! My name is wangjinghsuai!

例2:

public class StringTestTwo {
public static void main(String[] args){
String str = new String("Hello,");
String str1 = str.concat("teacher!");
System.out.println(str1);

}
}

打印的结果为:
Hello,teacher!

转载文章链接:http://blog.sina.com.cn/s/blog_9759d74d01019ru6.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: