主题:【游戏】不看不知道,一看吓一跳!!! -- Highway
兄弟我自以为在Java上还是有一两年功力的,结果没想到尽然让这两个小题给蒙蔽了,汉啊!!!
怎么样,你也下来玩玩?
问题一
有人写了这么段程序,意思是想无限循环,大家看看能不能Work
while (i <= j && j <= i && i != j) {
}
问题二
有这么两个Class,
public class PrintWords {
public static void main(String[] args) {
System.out.println(Words.FIRST + " " +
Words.SECOND + " " + Words.THIRD);
}
}
public class Words {
public static final String FIRST = "the";
public static final String SECOND = null;
public static final String THIRD = "set";
}
你编译以一下,没问题是吧。好,现在改动一下Words Class,如下
public class Words {
public static final String FIRST = "physics";
public static final String SECOND = "chemistry";
public static final String THIRD = "biology";
}
然后再把Words Class编译一下,再次运行,结果会是什么样的呢?
不要上Google找答案,自己想想看!!!
1。操作苻优先顺序问题,加括号就对了。
2。编译优化了Words.SECOND?
public class LongDivision {
private static final long MILLIS_PER_DAY
= 24 * 60 * 60 * 1000;
private static final long MICROS_PER_DAY
= 24 * 60 * 60 * 1000 * 1000;
public static void main(String[] args) {
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);
}
}
答案是多少呢?
5, 1000, 5000, Exception?
while (i <= j && j <= i && i != j) { }
条件还原一下,应该是这样的
if (i <= j) { if (j <= i) { if (i<>j) { do 循环里面的 } } }
所以呢,无论 i>j, i<j, i=j,都进不去循环里层的
有这么大区别阿?看来要补课了......
public static void main(String args[]) { System.out.println((new StringBuilder()).append("the ").append(Words.SECOND).append(" ").append("set").toString()); }
通过反编译就可以发现其中的秘密。也就是为什么改动了Words以后,结果是那个样子!
偶是学C的,没有对付java的经验
static long 不会只有32位吧?如果是MICRO_PER_DAY就溢出了,不知是报Exception还是就留尾巴?
如果是后者,应该是5?(用计算器算出来的,算作弊吗?
原来关键是static。
受教了。
在请教一下,这些会不会随编译器而不同?
一定是缺省整形数长度和数据转换惹得祸,应该是5?
24 * 60 * 60 * 1000 * 1000,结果是Overflow了。
最简单的办法是
24L * 60 * 60 * 1000 * 1000,这样中间结果都是存放在long中的。
直接使用Words class的fields的without creating a object first。
我觉得关键是final。因为final意味着不能修改,所以Java编译器想优化程序,把Words里的值直接拿进去了。不巧second是个null,被留在了外面。如果我们去掉final,java编译器就“老实”了。结果如下:
public static void main(String args[])
{
System.out.println((new StringBuilder()).append(Words.FIRST).append(" ").append(Words.SECOND).append(" ").append(Words.THIRD).toString());
}