- 18
- 0
- 约5.35万字
- 约 9页
- 2017-06-13 发布于河南
- 举报
jav易错经典试例
一.switch
public class TestSwitch {
public static void main(String[] args) {
int i = 2;
switch (i) {
case 1:
System.out.println(1);
case 2:
System.out.println(2);
case 3:
System.out.println(3);
default:
System.out.println(4);
}
}
}
结果:
2
3
4
分析:
少了break;所以2以下的case和default都执行了一遍。
二、Equals和==运算符
代码:
Java代码
public static void test() {
String x = hello;
String y = world;
String z = new String(helloworld);
String a = helloworld;
System.out.println(x+y equals z: + (x + y).equals(z));
System.out.println(a == z: + (a == z));
System.out.println(x == hello: + (x == hello));
System.out.println(a == helloworld: + (a == hello + world));
System.out.println(a == x+y: + (a == (x + y)));
}
结果:
x+y equals z:true
a == z:false
x == hello:true
a == helloworld:true
a == x+y:false
分析:
1.String.equals()方法比较的是字符串的内容,所以(x + y).equals(z)为true.
2.“==”比较的是 String 实例的引用,很明显 a 和z 并不是同一个 String 实例,所以(a == z)为false.
3.根据常量池的知识,容易得知(x == hello)和(a == hello + world)都为true.
(常量池指的是在编译期被确定并被保存在已编译的.class 文件中的一些数据。它包含了
关于方法、类、接口等,当然还有字符串常量的信息。也就是所谓的持久代。)
4.那么(a == (x + y))为什么是false呢?这点暂点有点不大清楚。初步认为是x+y是引用相加,不能放入常量池。
三、Override覆盖
代码:
Java代码
public class Parent {
public static String say() {
return parent static say;
}
public String say2() {
return parent say;
}
}
public class Child extends Parent {
public static String say() {
return child static say;
}
public String say2() {
return child say;
}
}
public class OverrideTest {
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.say());
System.out.println(p.say2());
}
}
结果:
parent static say
原创力文档

文档评论(0)