Java常用类__装箱/拆箱

以下是常用的各两种方法(各类提供了构造方法,静态方法)

一、基本数据类型 转化为 包装类(装箱

  例:int i=10;

    Integer num=i;//num=10

二、包装类 转化为  基本数据类型 (拆箱

  例:Integer num=10;

    int i=num;//i=10


三、基本数据类型  转化为 String类

  例:int i=10;

    String str=i+'' '';//  "10"

四、String类  转化为  基本数据类型

  例:String str="123";

    int i=Integer.parseInt(str);//123


五、包装类  转化为 String类

  例:Integer num=123;

    String str=num+"";//"123"

六、String类  转化为  包装类

  例:String str="123";

  Integer num=Integer.parseInt(str);//123


  随机数

一、Math

    公式为 (int)(Math.Random()*(Max-Min+1)+Min)

二、Random

    公式为 (int)(Random.nextInt(Max-Min+1)+Min)

例:  使用Math类随机产生100个2~99的的整数(包括2,包括99)

// 使用Math.random()产生随机数
  for (int i = 0; i < 100; i++) {
  System.out.print((int) (Math.random() * (99 - 2 + 1) + 2) + ",");

  if (i != 0 && i % 10 == 0) {
    System.out.println();
  }
}

 

// 使用Random类产生随机数
  Random r = new Random();
  System.out.println(r.nextInt());

  Random r1 = new Random(1000);// 提供种子
  System.out.println(r1.nextInt());
  Random r2 = new Random(1000);// 结果相同
  System.out.println(r2.nextInt());

  System.out.println();

  for (int i = 0; i < 100; i++) {
  System.out.print((int) (r2.nextInt(99 - 2 + 1)+ 2)+",");
  if (i != 0 && i % 10 == 0) {
  System.out.println();
  }
}

原文地址:https://www.cnblogs.com/64Byte/p/12167960.html