• 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();  //②--->手动拆箱

                        

              

  • 相关阅读:
    2019.9.25 初级数据结构——树状数组
    2019.9.29 陪审团
    2019.9.27 硬币
    0070-星星阵
    0069-简单的回文数问题
    0068-简单的求和问题
    0067-水仙花数
    0066-若干个数求和问题
    0065-数方块
    0064-简单的平方和
  • 原文地址:https://www.cnblogs.com/qiaoqiaoli/p/10762127.html
Copyright © 2020-2023  润新知