示例如下:
1 public class demo { 2
3 public static void main(String[] args) { 4
5 String s="10"; 6
7 //String是字符串數據類型;s是變量;10是字符串
8
9 int a =Integer.parseInt(s); 10
11 /*因兩者類型不匹配,不能從 String型 轉換為 int型; 12 * 13 * 則需要使用封裝類,將String字符類型數據轉換為Integer整型數據; 14 */
15
16 System.out.println("變量a的結果是"+a); 17
18 //使用“+”進行字符串和變量a的拼接;
19
20 s ="20"; 21
22 //變量s重新賦值;
23
24 System.out.println("重新賦值后變量a的結果是:"+s); 25
26
27 } 28
29 }
輸出結果為
1 變量a的結果是10 2 重新賦值后變量a的結果是:20
假如:
1 String s = " "
2 //" "字符串是空的或者是"a""b"....
示例如下:
1 public class demo { 2
3 public static void main(String[] args) { 4
5 String s = " "; 6
7 int a = Integer.parseInt(s); 8
9 System.out.println(a); 10
11
12 } 13
14 }
輸出結果:會出現異常
1 Exception in thread "main" java.lang.NumberFormatException: For input string: "a" 2 at java.lang.NumberFormatException.forInputString(Unknown Source) 3 at java.lang.Integer.parseInt(Unknown Source) 4 at java.lang.Integer.parseInt(Unknown Source)
5 at demo03.main(demo.java:7)
編譯可以通過,因為"s"有值,而運行時會出現數字轉換異常," "空的字符串不能轉換為int整數數據類型。