黑马程序员技术交流社区

标题: 关于String类的个人总结 [打印本页]

作者: fanfuhu1992    时间: 2016-3-16 00:21
标题: 关于String类的个人总结
1.String类(String类型):1.1字符串概述
        概述:就是由多个字符组成的一串数据。也可以看成是一个字符数组。
              String类下的方法无需导包,这里介绍的方法只有valueOf方法直接用类名就可以调用,其他的都需先创建对象来调用。
1.2String类型的特点:
A:字符串字面值"abc"也可以看成是一个字符串对象。(即定义一个字符串类型的变量,就是为String类创建了一个实例,可以通过变量名(索引)来调用String类中的方法。)                  
B:字符串是常量,一旦被赋值,就不能被改变。
(注意:指的是字符串的值不能变,但是引用是可以变的。)
file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml\wpsA160.tmp.jpg
1.3String类创建对象的两种方法及区别:
  AString s1 = new String("hello");
  BString s2= "hello";
   a前者会创建2个对象,后者创建1个对象;或者前者创建1个对象,后者无需创建对象。(如果方法区中有了“hello”字符串,那么就无需再在方法区创建表示“hello”的对象,那么前者只需创建一个对象,即堆中的对象,后者不需创建对象)
   b、注意:输出索引s1得出的是堆中开辟的地址值,s2则表示的是方法区中的地址值。
  
比较==equals用来比较String类的对象(即索引或称为变量名)时的区别:
  ==:比较引用类型比较的是地址值是否相同
  equals:String类重写了equals()方法,比较的是内容是否相同。(比较引用类型,原本默认的是比较地址值是否相同。)
file:///C:\Users\lenovo\AppData\Local\Temp\ksohtml\wpsA171.tmp.jpg
看程序写结果
public class StringDemo3 {
        public static void main(String[] args) {
                String s1 = new String("hello");
                String s2 = new String("hello");
                System.out.println(s1 == s2);// false
                System.out.println(s1.equals(s2));// true
                String s3 = new String("hello");
                String s4 = "hello";
                System.out.println(s3 == s4);// false
                System.out.println(s3.equals(s4));// true
                String s5 = "hello";
                String s6 = "hello";
                System.out.println(s5 == s6);// true
                System.out.println(s5.equals(s6));// true
        }
}
1.4String类型的变量或常量相加的区别:
   A、字符串如果是变量相加,先开空间,再拼接。
   B、字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回(即无需创建对象),否则,就创建对象。
看程序写结果
*/
public class StringDemo4 {
        public static void main(String[] args) {
                String s1 = "hello";
                String s2 = "world";
                String s3 = "helloworld";
                System.out.println(s3 == s1 + s2);// false
                System.out.println(s3.equals((s1 + s2)));// true
                System.out.println(s3 == "hello" + "world");// false 这个我们错了,应该是true
                System.out.println(s3.equals("hello" + "world"));// true
                // 通过反编译看源码,我们知道这里已经做好了处理。
                // System.out.println(s3 == "helloworld");
                // System.out.println(s3.equals("helloworld"));
        }
}


作者: fanfuhu1992    时间: 2016-3-16 00:23
这次的总结都是字符串的概述与特点描述,下次发它的功能总结,感觉String非常重要,一定要好好掌握




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2