JAVA基础(String类构造方法)

1,String类的构造方法

2,常见构造方法

  • public String():空构造

  • public String(byte[] bytes):把字节数组转成字符串

  • public String(byte[] bytes,int index,int length):把字节数组的一部分转成字符串

  • public String(char[] value):把字符数组转成字符串

  • public String(char[] value,int index,int count):把字符数组的一部分转成字符串

  • public String(String original):把字符串常量值转成字符串

3,案例

扫描二维码关注公众号,回复: 6524850 查看本文章
public static void main(String[] args) {

        String s1 = new String();

        System.out.println(s1);

        

        byte[] arr1 = {97,98,99};        

        String s2 = new String(arr1);            //解码,将计算机读的懂的转换成我们读的懂

        System.out.println(s2);

        

        byte[] arr2 = {97,98,99,100,101,102};

        String s3 = new String(arr2,2,3);        //将arr2字节数组从2索引开始转换3个

        System.out.println(s3);

        

        char[] arr3 = {'a','b','c','d','e'};    //将字符数组转换成字符串

        String s4 = new String(arr3);

        System.out.println(s4);

        

        String s5 = new String(arr3,1,3);        //将arr3字符数组,从1索引开始转换3个

        System.out.println(s5);

        

        String s6 = new String("xiaoshuai");

        System.out.println(s6);

    }

  S2  =  a b c ;    s3 =  c d e   ;      s4 = abcde ;   s5 =   bcd;     s6 =xioashuai;

4,判断定义为String类型的s1和s2是否相等

 String s1 = "abc";

 String s2 = "abc";

 System.out.println(s1 == s2);                     true

 System.out.println(s1.equals(s2));              true

String 创建的值在常量池中。判断时。先看常量池中有么有。有就使用。没有就创建之后再使用。

5,下面这句话在内存中创建了几个对象?

    * String s1 = new String("abc");            

创建了两个对象。常量池中一个对象。堆内存中一个对象。堆内存的对象是常量池中的副本。

6,判断定义为String类型的s1和s2是否相等

String s1 = new String("abc");                //记录是堆内存的地址值

String s2 = "abc”;                                   //记录常量池中的地址值

System.out.println(s1 == s2);                    false

System.out.println(s1.equals(s2));             true

7,判断定义为String类型的s1和s2是否相等    

String s1 = "a" + "b" + "c”;                在编译的时候就编程了abc

String s2 = "abc";

System.out.println(s1 == s2);                        true

System.out.println(s1.equals(s2));                 true

java 中有常量优化机制。



8,判断定义为String类型的s1和s2是否相等

String s1 = "ab";

String s2 = "abc";

String s3 = s1 + "c";

System.out.println(s3 == s2);                           true

System.out.println(s3.equals(s2));                    false

      

猜你喜欢

转载自blog.csdn.net/Cricket_7/article/details/92565405