Java如何將字符串轉(zhuǎn)為數(shù)字int的三種方式詳析
如何將java字符串轉(zhuǎn)換為數(shù)字
對知識永遠(yuǎn)只有學(xué)無止境。
第一種
String str = "123456"; Integer num = new Integer(str);//轉(zhuǎn)換成對象
第二種
String str = "123456"; int num = Integer.parseInt(str);
第三種
String str = "123456"; int num = Integer.valueOf(str);
注意:這三種的轉(zhuǎn)換區(qū)別在哪里呢?對知識應(yīng)該敬畏。
第一種是將字符串,轉(zhuǎn)換成一個數(shù)字的對象,兩個相同的數(shù)字進行轉(zhuǎn)換。
Integer num = new Integer("1");//轉(zhuǎn)換成對象 Integer num1 = new Integer("2");//轉(zhuǎn)換成對象 if (num == num1) { System.out.println("相等"); }else{ System.out.println("不相等"); }
結(jié)果:不相等
第二種:多次的解析,最終的得到結(jié)果,可以用 “==”進行判斷相等
String s = "123456"; if (Integer.parseInt(s) == Integer.parseInt(s)) { //結(jié)果true System.out.println("兩者相等"); }
結(jié)果:兩者相等
第三種:多次解析會存在不相等的時候,具體請看需要看轉(zhuǎn)換的字符整體大小決定的。
例子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)"); }
結(jié)果:
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)"); }
結(jié)果:
i1 != i2
i1.equals(i2)
因上述可知:數(shù)值為1000,不在-128~127之間,通過Integer.valueOf(s)解析出的兩個對象i1和i2是不同的對象,對象中的value值是相同的。
原因: 因為在JDK源碼當(dāng)中時已經(jīng)定義好的,由于在-128 ~ 127之間的整數(shù)值用的比較頻繁,每一次的創(chuàng)建直接從緩存中獲取這個對象,所以value值相同的Integer對象都是對應(yīng)緩存中同一個對象。-128~127之外的整數(shù)值用的不太頻繁,每次創(chuàng)建value值相同的Integer對象時,都是重新創(chuàng)建一個對象,所以創(chuàng)建的對象不是同一個對象。
總結(jié)
到此這篇關(guān)于Java如何將字符串轉(zhuǎn)為數(shù)字int的三種方式的文章就介紹到這了,更多相關(guān)Java字符串轉(zhuǎn)數(shù)字int內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中do-while循環(huán)的使用方法及注意事項詳解
這篇文章主要介紹了Java中do-while循環(huán)的使用方法及注意事項的相關(guān)資料,在Java編程中,do-while循環(huán)是一種基本的循環(huán)控制結(jié)構(gòu),它至少執(zhí)行一次循環(huán)體,然后根據(jù)條件判斷是否繼續(xù),文中將用法介紹的非常詳細(xì),需要的朋友可以參考下2024-10-10