Java 八种基本类型和基本类型封装类

  1.首先,八种基本数据类型分别是:int、short、float、double、long、boolean、byte、char;

     它们的封装类分别是:Integer、Short、Float、Double、Long、Boolean、Byte、Character。

 
数据类型  包 装 类 字节长度 默 认 值
int Integer 4 0
short Short 2 0
long Long 8 0l或0L
byte Byte 1 0
float Float 4 0.0F或0.0f
double Double 8 0.0
char Character 2 u0000
boolean Boolean 1 false

  2.Java中的数值都是有符号的,不存在无符号的数,它们的取值范围也是固定的,不会随着硬件环境或者操作系统的改变而改变。

  3.原始数据类型在传递参数时都是按值传递,封装类都是按引用传递。

  4.Java语言中,默认声明的小数是double类型的,因此对float类型的变量进行初始化时需要进行类型转换。

     float类型变量有两种初始化方法:float f = 1.0f  或者 float f =(float) 1.0 。

  5."=="和"equals()"方法:

    1)基本型和基本型封装型进行“==”运算符的比较,基本型封装型将会自动拆箱变为基本型后再进行比较,因此Integer(0)会自动拆箱为int类型再进行比较,显然返回true。

    2)两个Integer类型进行“==”比较,如果其值在-128至127,那么返回true,否则返回false, 这跟Integer.valueOf()的缓冲对象有关,这里不进行赘述。

    3)两个基本型的封装型进行equals()比较,首先equals()会比较类型,如果类型相同,则继续比较值,如果值也相同,返回true。

    4)基本型封装类型调用equals(),但是参数是基本类型,这时候,先会进行自动装箱,基本型转换为其封装类型,再进行3)中的比较。

     int i=0;
        Integer j=new Integer(0);
        System.out.println(i==j);
        System.out.println(j.equals(j));
        double d=0.5;
        Double b=new Double(0.5);
        System.out.println(d==b);
        System.out.println(b.equals(d));
        Integer aa=-100;
        Integer bb=-100;
        System.out.println(aa==bb);
        Integer aaa=129;
        Integer bbb=129;
        System.out.println(aaa==bbb);

 

    程序运行结果:

true
true
true
true
true
false

 

  6.不同数据类型之间的转换规则:

    在Java中当参与运算的两个变量的数据类型不同时,就需要进行隐式的数据类型转换,转换规则为:从低精度向高精度转换,即优先级满足byte<short<char<int<long<float

<double.反之,则需要通过强制类型转换来完成。

 

常见的自动类型转换的规则
   操作数1的类型    操作数2的类型     转换后的类型
    int  

  byte,short,char

    int
    long

  byte,short,char,int

    long
    float

  byte,short,char,int,long

    float

    double

  byte,short,char,int,long,float     double

 

    l类型自动转换时,需要注意的几点:

      1)char数据类型转换为高级类型时,会自动转换为其对应的ASCII码。

      2)byte, char, short 类型的数据在参与运算时会自动转换为int类型,但当使用''+=" 运算符时就不会产生类型转换,例如 short s1= 1; s1=(shot) (s1+1) 。short s2 = 1;s1+=1。

      3)基本数据类型不能与boolean类型相互转换。

 

 

强制类型转换的规则
  原操作数的类型     转换后操作数的类型
  byte   char
  char   byte char
  short   byte char
  int   byte short char
  long   byte short char int
  float   byte short char int long
  double   byte short char int long double

    需要注意的是,在进行强制类型转换时可能会损失精度。

posted @ 2017-09-14 14:07  戏路很宽丶  阅读(13839)  评论(0编辑  收藏  举报