Java中String的几个常用构造方法

关于String类常用的构造方法:

1、String s = “”; (这是用的最多的)

2、String s = new String("");

3、String s = new String(byte[] bytes);

4、String s = new String(byte[] bytes, int offset, int length);

5、String s = new String(char[] chars);

6、String s = new String(char[] chars, int offset, int length);


测试代码:

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

        //用的最多的字符串初始化是
        String s1 = "hello world";
        System.out.println(s1);  //输出:hello world

        //new String(String str)
        String s2 = new String("good job");
        System.out.println(s2);  //输出:good job

        //new String(byte[] bytes)
        byte[] bytes = {97, 98, 99, 100};  //48-57:0-9   65-90:A-Z   97-122:a-z
        String s3 = new String(bytes);
        System.out.println(s3);  //输出:abcd

        //new String(byte[] bytes, int offset, int length)   其中offset是数组的起始下标,length是长度
        String s4 = new String(bytes, 1, 3);
        System.out.println(s4);  //输出:bcd

        //new String(char[] chars)
        char[] chars = {'s', 't', 'u', 'd', 'e', 'n', 't'};
        String s5 = new String(chars);
        System.out.println(s5);  //输出:student

        //new String(char[] chars, int offset, int length)
        char[] chars1 = {'我', '是', '中', '国', '人'};
        String s6 = new String(chars1, 2, 3);
        System.out.println(s6);  //输出:中国人

    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值