包装类
概述 :Java提供了两个类型系统,基本类型与引用类型,使用基本类型在于效率,然而很多情况,会创建对象使用,因为对象可以做更多的功能,如果想要我们的基本类型像对象一样操作,就可以使用基本类型对应的包装类,如下:
int和String类型的相互转换
int转换为String
- 方式一:直接在数字后加一个空字符串
- 方式二:通过String类静态方法valueOf()
示例代码
public class IntegerDemo { public static void main(String[] args) { //int --- String int number = 100; //方式1 String s1 = number + ""; System.out.println(s1); //方式2 //public static String valueOf(int i) String s2 = String.valueOf(number); System.out.println(s2); } }
String转换为int
- 方式一:先将字符串数字转成Integer,再调用valueOf()方法
- 方式二:通过Integer静态方法parseInt()进行转换
示例代码
public class IntegerDemo { public static void main(String[] args) { //String --- int String s = "100"; //方式1:String --- Integer --- int Integer i = Integer.valueOf(s); //public int intValue() int x = i.intValue(); System.out.println(x); //方式2public static int parseInt (String s) int y = Integer.parseInt(s); System.out.println(y); } }
案例需求 :有一个字符串:“91 27 46 38 50”,请写程序实现最终输出结果是:“27 38 46 50 91”
import java.util.Arrays; public class IntegerTest { public static void main(String[] args) { //定义一个字符串 String s = "91 27 46 38 50"; //把字符串中的数字数据存储到一个int类型的数组中 String[] strArray = s.split(" "); //定义一个int数组,把 String[] 数组中的每一个元素存储到 int 数组中 int[] arr = new int[strArray.length]; for (int i = 0; i < arr.length; i++) { arr[i] = Integer.parseInt(strArray[i]); } //对 int 数组进行排序 Arrays.sort(arr); //把排序后的int数组中的元素进行拼接得到一个字符串,这里拼接采用StringBuilder来实现 StringBuilder sb = new StringBuilder(); for (int i = 0; i < arr.length; i++) { if (i == arr.length - 1) { sb.append(arr[i]); } else { sb.append(arr[i]).append(" "); } } String result = sb.toString(); //输出结果 System.out.println(result); } }
装箱与拆箱
基本类型与对应的包装类对象之间,来回转换的过程称为”装箱“与”拆箱“:
- 装箱:从基本类型转换为对应的包装类对象。
- 拆箱:从包装类对象转换为对应的基本类型。
用Integer与 int为例:
BigInteger类
- 由来:Integer类作为int的包装类,能存储的最大整型值为2 31-1,Long类也是有限的, 最大为2 63-1。如果要表示再大的整数,不管是基本数据类型还是他们的包装类 都无能为力,更不用说进行运算了。
- java.math包的BigInteger可以表示不可变的任意精度的整数。BigInteger 提供 所有 Java 的基本整数操作符的对应物,并提供 java.lang.Math 的所有相关方法。 另外,BigInteger 还提供以下运算:模算术、GCD 计算、质数测试、素数生成、 位操作以及一些其他操作。
构造器
- BigInteger(String val):根据字符串构建BigInteger对象
常用方法
- public BigInteger abs():返回此 BigInteger 的绝对值的 BigInteger。
- BigInteger add(BigInteger val) :返回其值为 (this + val) 的 BigInteger
- BigInteger subtract(BigInteger val) :返回其值为 (this - val) 的 BigInteger
- BigInteger multiply(BigInteger val) :返回其值为 (this * val) 的 BigInteger
- BigInteger divide(BigInteger val) :返回其值为 (this / val) 的 BigInteger。整数 相除只保留整数部分。
- BigInteger remainder(BigInteger val) :返回其值为 (this % val) 的 BigInteger。
- BigInteger[] divideAndRemainder(BigInteger val):返回包含 (this / val) 后跟 (this % val) 的两个 BigInteger 的数组。
- BigInteger pow(int exponent) :返回其值为 (thisexponent) 的 BigInteger。
BigDecimal类
- 一般的Float类和Double类可以用来做科学计算或工程计算,但在商业计算中, 要求数字精度比较高,故用到java.math.BigDecimal类。 BigDecimal类支持不可变的、任意精度的有符号十进制定点数。
- 对于不需要任何准确计算精度的数字可以直接使用float或double,但是如果需要精确计算的结果,则必须使用BigDecimal类,而且使用BigDecimal类也可以进行大数的操作
构造器
- public BigDecimal(double val)
- public BigDecimal(String val)
常用方法