java基础知识随笔2--变量类型范围和操作方法

来源:互联网 发布:一钻淘宝店多少钱 编辑:程序博客网 时间:2024/06/09 20:49

</pre>1、JAVA提供位运算符,&, |, ^,  ~.位运算是逐位运算 10010001 & 01000001结果是00000001。~将所有位0变1,1变0.<p></p><p><span style="white-space:pre"></span>java提供的逻辑运算和位运算是不同的。&&和&的差异。</p><p>2、float PI = 3.14 这句话在java中是<strong>错误</strong>的,这是因为在程序中写下一个浮点数时,编译程序默认会使用double类型,把double数据给float,会有精度丢失报错,方法:</p><p><span style="white-space:pre"></span>float PI = 3.14F;</p><p><span style="white-space:pre"></span>float PI = (float) 3.14;</p><p><span style="white-space:pre"></span>但是:byte number = 10;整数形的<span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">Literal constant默认使用的是不超过int类型长度, 将一个 常量10赋给一个byte变量时,这里10的长度就是byte的长度。byte number = 128;就提示错误了,因为byte存不了128。 long number1 = 2147683648;会报错,因为整形常数<span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">默认是不超过int类型长度,<span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">2147683648已经超过了int长度的范围。解决方法是<span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">long number1 = 2147683648L;</span></span></span></span></p><p><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">3、int a = 3; short number = a;这样会有精度可能丢失的报错出现,所以将一个整形<strong>常量</strong>(默认为长度不超过int类型)赋给short、byte都是没问题的,但是将一个int<strong>变量</strong>一个short、byte变量就会提示精度丢失错误。</span></span></span></span></p><p><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px">4、java在做运算整数时,如果全部的操作数都是不大于int的范围(不看操作数的变量类型),那么一律在int的空间中计算:</span></span></span></span></p><p><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><span style="color:rgb(51,51,51); font-family:Arial; font-size:14px; line-height:26px"><span style="white-space:pre"></span></span></span></span></span></p><pre name="code" class="java"><span style="white-space:pre"></span><pre name="code" class="java">short a = 1;short b = 2;short c  = a + b;

提示错误。解决方法 short c = (short)(a+b);

short a = 1;short b = 2;int c  = a + b;

没有问题。


如果表达式中包括不同类型,则运算时会以最长的类型为主,如下:

short a = 1;long   b = 2;int      c  = a+b;  

会提示有精度丢失错误,因为在a+b的计算过程中,结果已经变成了long型。所以应改为 int c = (int)(a+b);

0 0