1、a=a+b和a+=b的区别
对于同样类型的a,b来说
两个式子执行的结果确实没有什么区别。但是从编译的角度看吧(武让说的),a+=b;执行的时候效率高。
对于不同类型的a,b来说
不同类型的两个变量在进行运算的时候,我们经常说到的是类型的转换问题。这里,记住两点:一、运算过程中,低精度的类型向高精度类型转换。二、如果将高精度的数值赋值给低精度类型变量,则必须要进行显性的强制转换。
对于a+=b;这个式子,要明确的一点是,+=运算中,结合了强制类型转换的功能,因此,不会出现编译错误;而对于a=a+b;这个式子,因为是简单的运算,没有类型转换,在编译过程中会报错。
2、3*0.1 == 0.3 返回 true还是 false
返回false因为有些浮点数不能完全精确的表示出来。
public static void main(String[] args) {
System.out.println(3 * 0.1);
System.out.println(4 * 0.1);
System.out.println(3 * 0.1 == 0.3);
System.out.println(13 * 0.1 == 1.3);
System.out.println(9 * 0.1 == 0.9);
System.out.println(3 * 0.1 / 3);
}
结果是:
0.30000000000000004
0.4
false
true
true
0.10000000000000002
3、能在 Switch 中使用 String 吗?
从 Java 7 开始,我们可以在 switch case 中使用字符串,但这仅仅是一个语法糖。内部实现在 switch 中使用字符串的 hashCode。
在JDK7以前,switch是不能够用String作为参数进行条件判断的,只能支持 byte、short、char、int或者其对应的封装类以及 enum 类型。但是在JDK之后,String作为参数是能够作为switch的参数,但是前提是你的jdk环境必须是JDK7以上的版本。
这里我们看一下代码(这里用的jdk环境为jdk1.7.0_79):
public class SwitchDemo {
public static void main(String[] args) {
String string = "Hello";
switch (string) {
case "Hello":
System.out.println("Application is running on Hello mode");
break;
case "World":
System.out.println("Application is running on World mode");
break;
case "Java":
System.out.println("Application is running on Java mode");
break;
default:
System.out.println("Application is running on default mode");
break;
}
}
}
最后结果输出无疑为:Application is running on Hello mode,所以咋jdk1.7以上是能够以String作为Switch为参数的。但是值得思考的是,java中是真的支持了这一特性还是另有玄机呢,所以我们一起来看看生成的.class文件,我们利用反编译器来一探究竟:
import java.io.PrintStream;
public class SwitchDemo
{
public SwitchDemo()
{
}
public static void main(String args[])
{
label0:
{
String string = "Hello";
String s;
switch ((s = string).hashCode())
{
default:
break;
case 2301506:
if (!s.equals("Java"))
break;
System.out.println("Application is running on Java mode");
break label0;
case 69609650:
if (s.equals("Hello"))
{
System.out.println("Application is running on Hello mode");
break label0;
}
break;
case 83766130:
if (!s.equals("World"))
break;
System.out.println("Application is running on World mode");
break label0;
}
System.out.println("Application is running on default mode");
}
}
}
从上面反编译的代码中我们可以知道,jdk1.7并没有新的指令来处理switch string,而是通过调用switch中string.hashCode,将string转换为int从而进行判断。
最后可以得到结论:jdk1.7以后可以将String作为switch参数进行传递,其原理就是将字符串转换成hashCode值,然后在进行equals比较,也就是编译器在编译期间给代码做了转换。