码迷,mamicode.com
首页 > 移动开发 > 详细

Wrapper-装箱和拆箱

时间:2017-04-23 18:50:22      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:sel   jdk1.5   封装   static   max   静态   system   oct   区别   

基本数据类型:栈
  byte, short,int,long,float,double,char,boolean
包装类型: 都处在java.lang包(不需要导包)
  Byte, Short,Integer,Long,Float,Double,Character,Boolean
  Integer中常用的方法:
    parseInt(String x):将字符串转为int类型
  数值类型常用的方法:Xxx:具体的数据类型
    parseXxx(String x):将字符串x转换为指定的数组类型Xxx
    parseInt,parseLong,parseFlot,parseDouble...
  1.什么是包装类型:堆(在内存中的消耗比较大)
    包装类是将基本类型封装到一个类中,然后提供常用的属性和方法
  2.为什么要用包装类型?
    a.在程序处理过程有些时候需要使用对象类型
    b.包装类型(类):其中提供一些属性和方法,方便操作
  JDK1.5之后Java支持自动装箱和拆箱
  装箱:将基本数据类型转化为包装类型:调用构造函数 或调用静态valueOf方法
    a.Integer num = new Integer(10);
    b.Integer num = Integer.valueOf(10);
  拆箱:将包装类型转为基本数据类型:对象名.xxValue():
    Integer a = Integer.valueOf(10);
    int b = Integer.intValue(a);

public class WrapperDemo {
    public static void main(String[] args) {
//        List list = new ArrayList();
//        list.add(new Integer(1));//将基本数据类型转换为对象类型
//        list.add(new Double(3.14));
//        Integer num = new Integer(10);
        Integer num = Integer.valueOf(10);
        int num2 = num.intValue();//将包装类型转换为基本数据类型
        System.out.println("Integer-->max_value="+Integer.MAX_VALUE);
        System.out.println("Integer-->min_value="+Integer.MIN_VALUE);
        System.out.println("Integer-->SIZE="+Integer.SIZE);
        System.out.println(Integer.toBinaryString(10));//将指定的数值转化为2进制
        System.out.println(Integer.toHexString(10));//将指定的数值转化为16进制
        System.out.println(Integer.toOctalString(10));//将指定的数值转化为8进制
        String str="12";
        String str2="34";
//        System.out.println(str+str2);//字符拼接
        int  a = Integer.parseInt(str);//将字符串转换为int类型
        int  b = Integer.parseInt(str2);
        System.out.println(a+b); 
        //JDK1.5支持自动装箱(基本类型--->包装类型)和拆箱(包装类型--->基本类型)操作
        Double d=3.14;//自动装箱
        double d2=d;//自动拆箱
    }
}

==与equals的区别:
  ==比较对象的话比较是的地址的引用是否相等
  equals:比较是对象的内容是否相等
Integer num3=123;//自动装箱
  ==>Integer num3=Integer.valueOf(123);

public class WrapperDemo2 {
    public static void main(String[] args) {
        Integer num1=new Integer(123);
        Integer num2=new Integer(123);
        System.out.println(num1==num2);//false
        System.out.println(num1.equals(num2));//true
        System.out.println("-----------------------");
//        Integer num3=123;//Integer num3=Integer.valueOf(123);
//        Integer num4=Integer.valueOf(123);
        Integer num3=1234;//Integer num3=Integer.valueOf(1234);
        Integer num4=Integer.valueOf(1234);
        System.out.println(num3==num4);//false
        System.out.println(num3.equals(num4));//true
        
        
    }
}

 

Wrapper-装箱和拆箱

标签:sel   jdk1.5   封装   static   max   静态   system   oct   区别   

原文地址:http://www.cnblogs.com/fwdsz/p/6753360.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!