小工具知识网

当前位置: 首页 > 行业知识 > Java如何将字符串转为数字int(三种方式)

行业知识

Java如何将字符串转为数字int(三种方式)

2026-12-04 15:33:34 来源:互联网转载

如何将java字符串转换为数字

对知识永远只有学无止境。

()
  1. 第一种
String str = "123456"; Integer num = new Integer(str);//转换成对象
  1. 第二种
String str = "123456";int num = Integer.parseInt(str);
  1. 第三种
String str = "123456";int num = Integer.valueOf(str);

注意:这三种的转换区别在哪里呢?对知识应该敬畏。

第一种是将字符串,转换成一个数字的对象,两个相同的数字进行转换。

()
  Integer num = new Integer("1");//转换成对象        Integer num1 = new Integer("2");//转换成对象        if (num == num1) {                 System.out.println("相等");        }else{        System.out.println("不相等");        }        

结果:不相等

第二种:多次的解析,最终的得到结果,index.php/tags-653.html" >可以用 “==”进行判断相等

String s = "123456";        if (Integer.parseInt(s) == Integer.parseInt(s)) { //结果true            System.out.println("两者相等");        }

结果:两者相等

第三种:多次解析会存在不相等的时候,具体请看需要看转换的字符整体大小决定的。

例子1:

         Integer i1 = Integer.valueOf("100");        Integer i2 = Integer.valueOf("100");        if (i1 == i2) { //两个对象相等            System.out.print("i1 == i2");        }        if (i1.equals(i2)) { //两个对象中的value值相等            System.out.print("i1.equals(i2)");        }

结果:

i1 == i2

i1.equals(i2)

例子2:

         Integer i1 = Integer.valueOf("100000");        Integer i2 = Integer.valueOf("100000");        if (i1 != i2) { //两个对象相等            System.out.print("i1 != i2");        }        if (i1.equals(i2)) { //两个对象中的value值相等            System.out.print("i1.equals(i2)");        }

结果:

i1 != i2

i1.equals(i2)

因上述可知:数值为1000,不在-128~127之间,通过Integer.valueOf(s)解析出的两个对象i1和i2是不同的对象,对象中的value值是相同的。

原因: 因为在JDK源码当中时已经定义好的,由于在-128 ~ 127之间的整数值用的比较频繁,每一次的创建直接从缓存中获取这个对象,所以value值相同的Integer对象都是对应缓存中同一个对象。-128~127之外的整数值用的不太频繁,每次创建value值相同的Integer对象时,都是重新创建一个对象,所以创建的对象不是同一个对象。

上一篇:PHP小偷程序编写指南

下一篇:轻松调整图片大小,教你轻松改变图片KB的技巧!