String类构造方法

1、字符串类的默认构造方法

      String() 的构造方法是最简单的构造方法,是系统默认的构造方法,可以不带参数。

public class q{
    public static void main(String[] args){
        String str = new String(); 
        System.out.println(str);
        }
    }
该代码的输出结果为空。因为只初始化了str,并没有为str赋值。

2、字节参数的构造方法

"String(byte[] byte)"将整个字节数组中的元素作为字符串对象。

public class q{
    public static void main(String[] args){
        byte [] b = {97,98};
        String str = new String(b); 
        System.out.println(str);
        }
    }
输出结果如下:

这个构造方法的作用是输入字节,输出字节对应的字符串。97对应的ASCII码代表的字符是a。

3、获取指定字节的构造方法

"String(byte[] byte,int offset, int length)"是将字节数组offset位置到“length”长度结束这中间的字节数组转换成对应 的字符串。

public class q{
    public static void main(String[] args){
        byte [] b = {97,98,99,100,101};
        String str = new String(b,3,2); 
        System.out.println(str);
        }
    }

猜你喜欢

转载自blog.csdn.net/qq_42080635/article/details/81393803