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

2021-07-20 15:05

阅读:766

标签:height   lsp   ref   float   oat   blog   width   font   ext   

整理了一下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 

 

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

标签:height   lsp   ref   float   oat   blog   width   font   ext   

原文地址:https://www.cnblogs.com/tubybassoon/p/9511859.html


评论


亲,登录后才可以留言!