初识String和StringBuffer

来源:互联网 发布:sql 别名 as 编辑:程序博客网 时间:2024/05/22 07:57

刚开始接触编程的时候,估计很多朋友也会犯过这样一个错误:

     String s1=new String(“hello”);

     String s2=new String(“hello”);

     然后果断认为s1==s2;

 

现在开发过程中碰到,或者带着后面进来的新人们做项目中,每每碰到总是觉得特亲切,呵呵其实我三年前咱也是这样二过来的,但也竟成了美好的回忆O(∩_∩)O哈哈~

1. String StringBuffer 位于 java.lang 包中,这个包中的类使用的时候不用导入;

2.  String类一旦初始化就不可以改变,而 StringBuffer则可以

3.  Stringbuffer它用于封装内容可变的字符串。它可以使用 tostring()转换成 string 字符串,例如:

     String x = "a" + 4 + "c";

     编译时等效于

     String x = new StringBuffer().append("a").append(4).append("c").toString() ;

4.  字符串常量是一种特殊的匿名对象,举个例子:

      String s1 = ”hello”;

      String s2=”hello”;

      s1==s2; 因为他们指向同一个匿名对象。

 

      但如果这样定义:

      String s1=new String(“hello”);

      String s2=new String(“hello”);

      则 s1 != s2 ;

      因为则是后是两个不同的对象,因此是不会相等的!