在java中經(jīng)常會遇到需要對數(shù)據(jù)進行類型轉(zhuǎn)換的場景,String類型的數(shù)據(jù)轉(zhuǎn)為Int類型屬于比較常見的場景,主要有兩種轉(zhuǎn)換方法:
1. 使用Integer.parseInt(String)方法
2. 使用Integer.valueOf(String)方法
? 具體demo如下:
public void convert() {
// 1.使用Integer.parseInt(String)
String str1 = "31";
Integer num1 = Integer.parseInt(str1);
System.out.print("字符串31轉(zhuǎn)換為數(shù)字:");
System.out.println(num1);
// 2.使用Integer.valueOf(String)
String str2 = "32";
Integer num2 = Integer.valueOf(str2);
System.out.print("字符串32轉(zhuǎn)換為數(shù)字:");
System.out.println(num2);
}
? 執(zhí)行結(jié)果:
? 根據(jù)執(zhí)行結(jié)果可見,兩種方式都能完成字符串到整型的轉(zhuǎn)換。
注意點但需要注意的是,使用這兩種方法都有一個前提,那就是待轉(zhuǎn)換字符串的內(nèi)容必須為純數(shù)字。?
? 不難發(fā)現(xiàn)上面demo中的待轉(zhuǎn)換字符串都是"31"、"32"這種由純數(shù)字組成的字符串,如果待轉(zhuǎn)字符串中出現(xiàn)了除數(shù)字以外的其他字符,則程序會拋出異常。
? 如下demo所示,在字符串中加入小寫英文字母,并用try-catch語句包裹代碼段以捕捉會出現(xiàn)的異常。(因為我們已經(jīng)知道,帶字母的字符串轉(zhuǎn)換為整型會出現(xiàn)數(shù)字格式轉(zhuǎn)換的異常,所以選擇catch NumberFormatException)
public void convert() {
// 1.Integer.parseInt(String)
try {
String str1 = "31a";
Integer num1 = Integer.parseInt(str1);
System.out.print("字符串31a轉(zhuǎn)換為數(shù)字:");
System.out.println(num1);
} catch (NumberFormatException e) {
System.out.println("Integer.parseInt(String)方法執(zhí)行異常");
e.printStackTrace();
}
// 1.Integer.valueOf(String)
try {
String str2 = "32b";
Integer num2 = Integer.valueOf(str2);
System.out.print("字符串32b轉(zhuǎn)換為數(shù)字:");
System.out.println(num2);
} catch (NumberFormatException e) {
System.out.println("Integer.valueOf(String)方法執(zhí)行異常");
e.printStackTrace();
}
}
從執(zhí)行結(jié)果可見,這段代碼分別在Integer.parseInt(String)方法和Integer.valueOf(String)位置觸發(fā)了NumberFormatException,????其原因都是被轉(zhuǎn)換的字符串中存在英文字母,無法轉(zhuǎn)換成整型。?
? 我們可以通過查看源碼來比價兩個方法的性能:
public static int parseInt(String s) throws NumberFormatException {
return parseInt(s,10);
}
public static Integer valueOf(String s) throws NumberFormatException {
return Integer.valueOf(parseInt(s, 10));
}
? 不難發(fā)現(xiàn),Integer.parseInt(String) 和Integer.valueOf(String)的實現(xiàn)中,都是調(diào)用的一個方法:Integer.parseInt(String, Integer);但是Integer.valueOf(String)還多嵌套了一層Integer.valueOf(Integer)方法,因此從源碼可得知:Integer.parseInt(String)方法的性能更勝一籌。
你是否還在尋找穩(wěn)定的海外服務(wù)器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準(zhǔn)確流量調(diào)度確保服務(wù)器高可用性,企業(yè)級服務(wù)器適合批量采購,新人活動首月15元起,快前往官網(wǎng)查看詳情吧
當(dāng)前標(biāo)題:Java如何將字符串String轉(zhuǎn)換為整型Int-創(chuàng)新互聯(lián)
本文URL:http://chinadenli.net/article18/ddisdp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站設(shè)計公司、服務(wù)器托管、外貿(mào)網(wǎng)站建設(shè)、品牌網(wǎng)站設(shè)計、定制網(wǎng)站、微信小程序
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容