StringBuilder、StringBuffer和大数处理

59 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第21天,点击查看活动详情 >>

📖个人介绍

大家好我是:Zinksl

认真分享技术,记录学习点滴 如果分享对你有用请支持我哦🍺

点赞:👍 留言:✍收藏:⭐️ 个人格言: 想法落实的最佳时机就是现在!🏄


1 StringBuilder与StringBuffer的使用方法一样

1.1 如果字符串存在大量修改操作,一般使用StringBuffer或者StringBuilder

1.2 如果字符串存在大量修改操作,且单线程,使用StringBuilder

1.3 如果字符串存在大量修改操作,且多线程,使用StringBuffer

1.4 如果字符串很少修改,被多个对象引用,使用String,比如配置信息

2 大数处理

2.1 大整数的处理使用BigInteger

代码示例:

public class BigNumber {
    public static void main(String[] args) {
        BigInteger bigInteger = new BigInteger("123456789123456");
        BigInteger bigInteger2 = new BigInteger("123321");
        BigInteger temp;
//            加法
        temp = bigInteger.add(bigInteger2);
        System.out.println(bigInteger+"与"+bigInteger2+"的和为:"+temp);
//        减法
        temp = bigInteger.subtract(bigInteger2);
        System.out.println(bigInteger+"与"+bigInteger2+"的差为:"+temp);
//        乘法
        temp = bigInteger.multiply(bigInteger2);
        System.out.println(bigInteger+"与"+bigInteger2+"的积为:"+temp);
//        除法
        temp = bigInteger.divide(bigInteger2);
        System.out.println(bigInteger+"与"+bigInteger2+"的商为:"+temp);
    }
}

2.1 大小数处理使用

代码示例:

public class BigDecimaiDemo {
    public static void main(String[] args) {
        BigDecimal bd1 = new BigDecimal("15113151315131.15153151652");
        BigDecimal bd2 = new BigDecimal("5");
        BigDecimal temp;
//        加法
        temp = bd1.add(bd2);
        System.out.println("和为:"+temp);
//        减法
        temp = bd1.subtract(bd2);
        System.out.println("差为:"+temp);
//        乘法
        temp = bd1.multiply(bd2);
        System.out.println("积为:"+temp);
//        除法
        temp = bd1.divide(bd2);
        System.out.println("商为:"+temp);

    }
}

结语

大佬请留步在这里插入图片描述既然看到这了不如点个赞👍再走吧 本文目的在于分享技术以及在学习过程中个人记得需要注意的点,记录学习过程; 如果出现错误欢迎大家指正,如有意见或建议欢迎在评论区讨论