关于包装类的学习

包装类

包装类对应

基本数据类型包装类型
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
booleanBoolean
charCharacter

类型转换与装箱、拆箱

装修:把基本类型转换为引用类型。

拆箱:把引用类型转化为基本类型。

代码示例:

 
public class Demo01 {public static void main(String[] args) {​//JDK1.5之前//类型转换:装箱(基本类型转换为引用类型的过程)//基本类型int num1 = 19;//使用Integer类创建对象Integer integer1 = new Integer(num1);Integer integer2 = Integer.valueOf(num1);System.out.println("装修");System.out.println(integer1);System.out.println(integer2);​//类型转换:拆箱(引用类型转换为jib类型的过程)Integer integer3 = new Integer(100);int num2 = integer3.intValue();System.out.println("拆箱");System.out.println(num2);​//JDK1.5之后,提供自动装箱与拆箱int age = 30;//自动装修Integer integer4 = age;System.out.println("自动装修");System.out.println(integer4);​//自动拆箱int age2 = integer4;System.out.println("自动拆修");System.out.println(age2);}}

代码结果:

8种包装类提供不同类型间的转换方式

  • Number父类中提供的6个共性方法。

  • parseXXX()静态方法。

  • value()静态方法。

  • 注意:需要保证类型兼容,否则抛出NumberFormatException异常。

    代码示例:

    public class Demo01 {public static void main(String[] args) {​//基本类型和字符串之间转换//1.基本类型转成字符串int n1 = 255;//1.1使用+号String s1 = n1 + "";//1.2使用Integer中的toString()方法String s2 = Integer.toString(n1,16);  //fSystem.out.println(s1);System.out.println(s2);​//2.字符串转成基本类型String str = "150";//使用Integer.parseXXX();int n2 = Integer.parseInt(str);System.out.println(n2);​//boolean字符串类型装成基本类型。"true"-->true;  非"true"-->falseString str2 = "true";boolean b1 = Boolean.parseBoolean(str2);System.out.println(b1);}}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部