再美不及姑娘你
又见西风上碧树

Java基础——String构造方法

public String();创建一个空表字符串对象,不包含任何内容
public String(char[]chs); 根据字符数组的内容,来创建字符串对象,现已不用
public String (byte[]bys); 根据字节数组的内容,来创建字符串对象
String s="abs"; 直接赋值的方式创建字符串对象,内容为双引号内的字符串数据推荐使用
//笨方法
public class StringDemo01 {
  public static void main(String[] args) {
      //方式一
      String s = new String();
      System.out.println("s=" + s);
      //方式二,数组元素需要遍历
      char[] s2 = {'a', 'b', 'c'};
      System.out.print("s2=");
      //调用遍历数组方法
      PrintArr(s2);
      System.out.println();
      //方式三
      byte[] s3 = {5, 5, 5};
      System.out.print("s3=");
      //调用遍历数组方法
      PrintArr(s3);
      System.out.println();
      //方式四
      String s4 = "555";
      System.out.println("s4=" + s4);
  }

  //定义数组遍历方法
  public static void PrintArr(char[] arr) {
      System.out.print("[");
      for (int i = 0; i < arr.length; i++) {
          if (i == arr.length - 1) {
              System.out.print(arr[i]);
          } else {
              System.out.print(arr[i] + ",");
          }
      }
      System.out.print("]");
  }

  public static void PrintArr(byte[] arr) {
      System.out.print("[");
      for (int i = 0; i < arr.length; i++) {
          if (i == arr.length - 1) {
              System.out.print(arr[i]);
          } else {
              System.out.print(arr[i] + ",");
          }
      }
      System.out.print("]");
  }
}
//简洁方法
public class StringDemo02 {
  public static void main(String[] args) {
      //方式一
      String s = new String();
      System.out.println("s=" + s);
      //方式二,数组元素需要遍历
      char[] crs = {'a', 'b', 'c'};
      String s2 = new String(crs);
      System.out.println("s2=" + s2);
      //方式三
      byte[] byt = {5, 5, 5};
      String s3 = new String(crs);
      System.out.println("s3=" + s3);
      //方式四
      String s4 = "555";
      System.out.println("s4=" + s4);
  }
}

image-20220311183900669

   
   
posted on 2022-03-11 18:39  再美不及姑娘你  阅读(157)  评论(0)    收藏  举报