• 【Java】基本数据类型以及其转换


    整理了一下Java基本数据类型和面试可能涉及的知识。

         字节数(byte)  位数(bit)  取值范围
    整型  byte  1  8  -2^7 ~ 2^7 -1
    short   2  16  -2^15 ~ 2^15-1
    int*  4  32  -2^31 ~ 2^31-1 
    long   8  64  -2^63 ~ 2^63-1 
     浮点型   float   4  32  
    double*  8  64  
    字符型 char   2  16 0~2^16-1
    布尔型 boolean   1  

     

    整型的取值范围:

    最高位为符号,正负各2^(位-1)个数,0归为正数,故正数范围为0~2^(位-1)-1,负数为-2^(位-1)~-1

    浮点型的取值范围:

    float和double的范围是由指数的位数来决定的。没有搞清楚这个,迟点复习再看。

    https://www.cnblogs.com/BradMiller/archive/2010/11/25/1887945.html 这篇写得蛮好的

    1. 基本数据类型之间的转换

    参考:https://www.cnblogs.com/liujinhong/p/6005714.html

     低精度  →→   自动转换   →→  高精度 
    byte、char、short、int、long、float、double
    ←←   强制转换   ←←

    由于Java中默认整型数据使用int,浮点型使用double,故书写规范:

    byte a = 1;         //自动转换
    byte b = (byte)128;    //数值超出范围需作强制转换
    long c = 10000000000L;  //强制转换
    float d = 3.5f;      //强制转换
    double e = 3.5;

    进行数学运算时,数据类型会转换为涉及数据的最大形式

    int a = 2;
    byte b = 2;
    byte c = (byte)(a+b);
    double d = 5;
    char ch = (char)('a'+1);
    

    char型运算时会自动提升为int类型

    char a = 55;
    char b = 'a';
    char c = (char)(a+b);
    char d = 'a'+'a';
    System.out.println(a);//7
    System.out.println(b);//a
    

    2. 基本数据类型的包装类及其转换

     基本数据类型   boolean  char byte short  int long float double
    包装类  Boolean Character Byte  Short  Integer  Long  Float  Double 

    装箱与拆箱

    Integer i = 10;  //装箱	基本类型 → 包装器类型
    int n = i;     //拆箱	包装器类型 → 基本类型
    

     查看对应.class文件可发现,以上代码实际调用的方法:

    Integer i = Integer.valueOf(10);
    int n = i.intValue();
    

    Integer(指向缓存/常量池) 和 new Integer(指向堆)由于指向内存位置不一样,比较时两者不等。

    ② Integer(非new)互相比较时,数值位于int取值范围内,比较结果为true,超出范围则为false

    ③ int和Integer/new Integer比较时,由于Integer会首先作拆箱处理与int比对,所以比较结果一定为true

    注:Double比较有所差别,所有Double的比较都为false

    详细可参详:https://www.cnblogs.com/dolphin0520/p/3780005.html 

    相关题目:

    1. 

    short s1 =1; s1 = 1+1; short s1 = 1; s1 +=1; 上述语句能否编译通过,为什么?

    short s1 = 1;
    s1 = 1+1; //计算时会转换成int类型,由于左方是short类型的数据,右边运算完没有进行强制转换,所以编译不通过
    
    short s1=1;
    s1 += 1; //因为“+=”是赋值运算符,不牵涉与其它类型的数字计算,也不会转成 int 类型的,所以编译通过
    
  • 相关阅读:
    超全面的vue.js使用总结
    Python3 [字典】类型 学习笔记
    Python3 [集合]类型 学习笔记
    Python 希尔排序法
    Python 堆排序法
    Python 归并排序法
    Python 冒泡排序法
    Python 选择排序法
    Python 快速排序法(转)
    Python 插入排序法
  • 原文地址:https://www.cnblogs.com/tubybassoon/p/9511859.html
Copyright © 2020-2023  润新知