String类的概述和构造方法对String的练习

package MyString;
/*
        String:字符串类
                由多个字符组成的一串数组
                字符串本质上是一个字符数组
        构造方法:
                String(String original) :把字符串数据封装成字符串对象
                String(char[] value) :把字符数组的数据封装成字符串对象
                String(char[] value, int offset, int count):把字符数组中的一部分数据封装成字符串对象
         注意:字符串是一种比较特殊的引用数据类型,直接输出字符串对象输出的是该对象的数据
 */
public class StringDemo {
    
    
    public static void main(String[] args) {
    
    
        //方式1
        //String(String original) :把字符串数据封装成字符串对象
        String s1=new String("hello");
        System.out.println("print s1:"+s1);

        //方式2
        //String(char[] value) :把字符数组的数据封装成字符串对象
        char[] arr={
    
    'h','e','l','l','o'};
        String s2=new String(arr);
        System.out.println("print s2:"+s2);

        //方式3
        //String(char[] value, int offset, int count):把字符数组中的一部分数据封装成字符串对象
        String s3=new String(arr,0,5);//offset从数组的索引开始,count往后运行几个
        //注意数组越界的问题,例如1,5,索引值1后只有四个元素,越界
        System.out.println("print s3:"+s3);

        //方式4
        //String 直接赋值字符串
        String s4="hello";
        System.out.println("print s4:"+s4);
    }
}

猜你喜欢

转载自blog.csdn.net/m0_52646273/article/details/114126514