Java-字符串问题

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

猜你喜欢

转载自blog.csdn.net/Cxy_357/article/details/50770436
今日推荐