基本类型包装类、System类、Math类

基本类型包装类:

字节型:byte Byte;

短整型:short Short;

整 型:int Integer

长整型:long Long

字符型:char Character

布尔型:boolean Boolean

浮点型:float Float

浮点型:double Double

public class Demo01 {
  public static void main(String[] args) {
  //字符串转基本数据类型
  String str="12";
  int num=Integer.parseInt(str);
  System.out.println(num+1);
  double num2=Double.parseDouble(str);
  System.out.println(num2);
  //基本数据类型转字符串:第一种方法
  System.out.println(""+12+1);
  //基本数据类型转字符串:第二种方法
  String s1=String.valueOf(88);
  String s2=String.valueOf(1.2);
  System.out.println(s1+1);
  System.out.println(s2+1);
  //基本数据类型转字符串:第三种方法
  String s3=Integer.toString(99);
  System.out.println(s3+1);
  }
}

public static void main(String[] args) {
  // 基本数据类型转包装类型:第一种方法
  Integer in=new Integer(123);
  Integer in2=new Integer("456");
  //基本数据类型转包装类型:第二种方法
  Integer in3=Integer.valueOf(789);
  Integer in4=Integer.valueOf("147");
  //包装类型对象转基本数据类型
  int i1=in.intValue();
  int i2=in2.intValue();
  System.out.println(i2+1);
}

自动拆箱:对象自动直接转成基本数值

自动装箱:基本数值自动直接转成对象


public static void main(String[] args) {
  // jdk1.5以后自动拆装箱
  //自动装箱:基本数据类型转包装类型对象
  Integer in=123;//Integer in=new Integer(123);
  //自动拆箱:包装类型对象转基本数据类型
  int i=in+3;//int i=in.inValue()+3;
}

常量池:当数值在byte范围之内时,进行自动装箱,不会新创建对象空间而是使用已有的空间。

public static void main(String[] args) {
  //byte常量池-128-127
  Integer in1=50;
  Integer in2=50;
  System.out.println(in1==in2);//true
  System.out.println(in1.equals(in2));//true
}

System类不能手动创建对象,因为构造方法被private修饰

public class Demo01 {
  public static void main(String[] args) {
    int[] arr={1,2,3,4,5,6};
    for(int i=arr.length-1;i>=0;i--){
      if(i==4){
        System.exit(0);
      }
      System.out.println(arr[i]);
    }
  }
}

public static void main(String[] args) {
  new Person();
  new Person();
  new Person();
  new Person();
  new Person();
  new Person();
  //调用垃圾回收器
  System.gc();
}

public static void main(String[] args) {
  int[] arr={99,98,97,22,11,0};
  int[] arr2=new int[3];
  //将arr前三个数组元素复制到arr2中
  System.arraycopy(arr, 0, arr2, 0, 3);
  //遍历
  for(int i=0;i<arr2.length;i++){
  System.out.println(arr2[i]);
  }
}

Math类:

public static void main(String[] args) {
  //求绝对值
  System.out.println(Math.abs(-1.2));
  //向上取整
  System.out.println(Math.ceil(12.3));
  //向下取整
  System.out.println(Math.floor(12.9));
  //求两个值的最大值
  System.out.println(Math.max(10, 9));
  //求两个值的最小值
  System.out.println(Math.min(10, 9));
  //求次幂
  System.out.println(Math.pow(2, 10));
  //求随机数
  System.out.println(Math.random());
  //四舍五入
  System.out.println(Math.round(12.5));
}

猜你喜欢

转载自www.cnblogs.com/boss-H/p/10954673.html
今日推荐