int-Integer-String之間的轉換方式


1.intInteger之間的轉換:

      1) int----->Integer

               自動裝箱

               Integer的構造方法

              調用Integer的靜態方法:static Integer valueOf(int i):返回一個指定int值的Integer對象

         代碼如下:

                          int a = 10;
                          Integer i1 = a; //①
                          Integer i2 = new Integer(a);  //②
                          Integer i3 = Integer.valueOf(a);   //③

     2) Integer------>int            

              ①自動拆箱

            調用Integer的方法:int intValue():以int類型返回該Integer的值

        示例代碼:

                        Integer a = new Integer(10);

                        int i1 = a;   //①
                        int i2 = a.intValue();   //②    

2.String和Integer之間的轉換:

    1) Integer---->String

           調用Integer的方法:String toString():返回該Integer對象的字符串形式

            調用Integer的靜態方法:static String toString(int i):返回一個指定整數的String對象

           調用String的靜態方法:static String valueOf(Object obj):返回任意類型的字符串形式

        示例代碼:

                        Integer a = new Integer(20);

                        String str1 = a.toString();   //①

                        String str2 = Integer.toString(a);  //②

                        String str3 = String.valueOf(a);   //③

    2) String---->Integer

            調用Integer的靜態方法:static Integer valueOf(String s):返回指定的 String 的值的 Integer 對象。

                 注意:這里的參數s必須是可以解析成整數的字符串,否則會報異常:NumberFormatException

         示例代碼:

                        String str = "123";
                        Integer i = Integer.valueOf(str);  //①

3.int和String之間的轉換:

    1) int------>String

            字符串拼接,使用+

            調用Integer的靜態方法:static String toString(int i):返回一個指定整數的String對象

           調用String的靜態方法:static String valueOf(int i):返回指定int值的字符串形式

      示例代碼:

                        int a = 5;
                       String s1 = a +""; //①
                       String s3 = Integer.toString(a);  //②
                       String s2 = String.valueOf(a);   //③

    2) String----->int

        調用Integer的靜態方法:static int parseInt(String s):將一個可以解析為整數的字符串解析為一個int值

          ②調用Integer的靜態方法:static Integer valueOf(String s):返回指定的 String 的值的 Integer 對象。【自動拆箱】

      示例代碼:

                     String str = "123";
                     int m1 = Integer.parseInt(str);  //①
                     int m2 = Integer.valueOf(str);   //②--->自動拆箱
                     int m3 = Integer.valueOf(str).intValue();  //②--->手動拆箱

                    

          

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM