美文网首页
Java 基本类型包装类概述,Integer类

Java 基本类型包装类概述,Integer类

作者: 蛋炒饭_By | 来源:发表于2018-01-11 08:49 被阅读11次

基本类型包装类概述

将基本数据类型封装成对象的好处在于可以在对象中定义更多的功能方法操作该数据。
常用的操作之一:用于基本数据类型与字符串之间的转换。
基本类型和包装类的对应
Byte,Short,Integer,Long,Float,Double,Character,Boolean

Integer类

为了让基本类型的数据进行更多的操作,Java就为每种基本类型提供了对应的包装类类型

Integer的构造方法

/*

  • Integer的构造方法:
  • public Integer(int value)
  • public Integer(String s)
  •     注意:这个字符串必须是由数字字符组成
    

*/
public class IntegerDemo {
public static void main(String[] args) {
// 方式1
int i = 100;
Integer ii = new Integer(i);
System.out.println("ii:" + ii);

    // 方式2
    String s = "100";
    // NumberFormatException
    // String s = "abc";//这个字符串必须是由数字字符组成
    Integer iii = new Integer(s);
    System.out.println("iii:" + iii);
}

}
String和int的相互转换

/*

  • int类型和String类型的相互转换
  • int -- String
  •     String.valueOf(number)
    
  • String -- int
  •     Integer.parseInt(s)
    

*/
public class IntegerDemo {
public static void main(String[] args) {
// int -- String
int number = 100;
// 方式1
String s1 = "" + number;
System.out.println("s1:" + s1);
// 方式2
String s2 = String.valueOf(number);
System.out.println("s2:" + s2);
// 方式3
// int -- Integer -- String
Integer i = new Integer(number);
String s3 = i.toString();
System.out.println("s3:" + s3);
// 方式4
// public static String toString(int i)
String s4 = Integer.toString(number);
System.out.println("s4:" + s4);
System.out.println("-----------------");

    // String -- int
    String s = "100";
    // 方式1
    // String -- Integer -- int
    Integer ii = new Integer(s);
    // public int intValue()
    int x = ii.intValue();
    System.out.println("x:" + x);
    //方式2
    //public static int parseInt(String s)
    int y = Integer.parseInt(s);
    System.out.println("y:"+y);
}

}

相关文章

网友评论

      本文标题:Java 基本类型包装类概述,Integer类

      本文链接:https://www.haomeiwen.com/subject/yfkanxtx.html