如何將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)文章來源:http://www.zghlxwxcb.cn/news/detail-646927.html
因上述可知:數(shù)值為1000,不在-128~127之間,通過Integer.valueOf(s)解析出的兩個對象i1和i2是不同的對象,對象中的value值是相同的。文章來源地址http://www.zghlxwxcb.cn/news/detail-646927.html
原因: 因為在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)建的對象不是同一個對象。
到了這里,關(guān)于Java如何將字符串轉(zhuǎn)為數(shù)字int(三種方式)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!