Java如何將字符串String轉換為整型Int
用法
在java中經(jīng)常會遇到需要對數(shù)據(jù)進行類型轉換的場景,String類型的數(shù)據(jù)轉為Int類型屬于比較常見的場景,主要有兩種轉換方法:
- 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轉換為數(shù)字:");
System.out.println(num1);
// 2.使用Integer.valueOf(String)
String str2 = "32";
Integer num2 = Integer.valueOf(str2);
System.out.print("字符串32轉換為數(shù)字:");
System.out.println(num2);
}執(zhí)行結果:

根據(jù)執(zhí)行結果可見,兩種方式都能完成字符串到整型的轉換。
注意點
但需要注意的是,使用這兩種方法都有一個前提,那就是待轉換字符串的內容必須為純數(shù)字。
不難發(fā)現(xiàn)上面demo中的待轉換字符串都是"31"、"32"這種由純數(shù)字組成的字符串,如果待轉字符串中出現(xiàn)了除數(shù)字以外的其他字符,則程序會拋出異常。
如下demo所示,在字符串中加入小寫英文字母,并用try-catch語句包裹代碼段以捕捉會出現(xiàn)的異常。(因為我們已經(jīng)知道,帶字母的字符串轉換為整型會出現(xiàn)數(shù)字格式轉換的異常,所以選擇catch NumberFormatException)
public void convert() {
// 1.Integer.parseInt(String)
try {
String str1 = "31a";
Integer num1 = Integer.parseInt(str1);
System.out.print("字符串31a轉換為數(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轉換為數(shù)字:");
System.out.println(num2);
} catch (NumberFormatException e) {
System.out.println("Integer.valueOf(String)方法執(zhí)行異常");
e.printStackTrace();
}
}從執(zhí)行結果可見,這段代碼分別在Integer.parseInt(String)方法和Integer.valueOf(String)位置觸發(fā)了NumberFormatException,其原因都是被轉換的字符串中存在英文字母,無法轉換成整型。

性能比較
我們可以通過使用System.nanoTime()來查看兩種方法執(zhí)行的時間差
public static void convert() {
// 1.Integer.parseInt(String)
String str1 = "321";
long before1 = System.nanoTime();
Integer.parseInt(str1);
long interval1 = System.nanoTime() - before1;
System.out.print("Integer.parseInt(String)的執(zhí)行時長(納秒):");
System.out.println(interval1);
// 1.Integer.valueOf(String)
String str2 = "332";
long before2 = System.nanoTime();
Integer.valueOf(str2);
long interval2 = System.nanoTime() - before2;
System.out.print("Integer.valueOf(String)的執(zhí)行時長(納秒):");
System.out.println(interval2);
}其中,interval1和interval2的值分別指兩個方法的執(zhí)行前后系統(tǒng)時間之差,單位是納秒,執(zhí)行多次后均可發(fā)現(xiàn),Integer.valueOf(String)方法的執(zhí)行時長要小于Integer.parseInt(String)方法,性能更優(yōu)

到此這篇關于Java如何將字符串String轉換為整型Int的文章就介紹到這了,更多相關Java String轉換為Int內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java中的構造方法(構造函數(shù))與普通方法區(qū)別及說明
這篇文章主要介紹了Java中的構造方法(構造函數(shù))與普通方法區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
如何在Spring?Boot微服務使用ValueOperations操作Redis集群String字符串
這篇文章主要介紹了在Spring?Boot微服務使用ValueOperations操作Redis集群String字符串類型數(shù)據(jù),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-06-06
Spring定時任務@Scheduled注解(cron表達式fixedRate?fixedDelay)
這篇文章主要為大家介紹了Spring定時任務@Scheduled注解(cron表達式fixedRate?fixedDelay)使用詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11

