Java中的String类

构造方法

  String:字符串类
        由多个字符组成的一串数据;其本质是一个字符数组;

  构造方法:
            String(String original):把字符串数据封装成字符串对象
            String(char[] value):把字符数组的数据封装成字符串
            String(char[] value, int offset, int count):把字符数组中的一部分数据封装成字符串对象
                                                         offset:从第几个索引开始        count:一共截取几个
package Test8;

public class StringDemo {
    public static void main(String[] args) {
        //String(String original) 
        String s = new String("hello");
        System.out.println(s);

        System.out.println("............");

        //String(char[] value)
        char[] arr = {'h','e','l','l','o'};
        String s1 = new String(arr);
        System.out.println(s1);

        System.out.println("............");

        //String(char[] value, int offset, int count)
        char[] arr1 = {'h','e','l','l','o'};
        String s2 = new String(arr1,1,4);
        System.out.println(s2);

        System.out.println("............");

        //直接赋值创建对象
        String s3 = "hello";
        System.out.println(s3);
    }
}

通过构造方法创建的对象和直接赋值创建的对象的区别

  1. 通过构造方法创建的对象在堆内存中
  2. 通过直接赋值创建的对象在方法区的常量池中
package Test8;

public class StringDemo2 {
    public static void main(String[] args) {
        String s1 = new String("hello");
        String s2 = "hello";
        String s3 = "hello";

        System.out.println("s1和s2地址值是否相同:"+(s1==s2));
        System.out.println("s1和s3地址值是否相同:"+(s1==s3));
        System.out.println("s2和s3地址值是否相同:"+(s2==s3));
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值