Java™ Puzzlers: Traps, Pitfalls, and Corner Cases摘录

来源:互联网 发布:程序员招聘很难吗 编辑:程序博客网 时间:2024/06/06 18:31

System.out.println(2.00 - 1.10);//not all decimals can be represented exactly using binary floating-point

final long MICROS_PER_DAY = 24 * 60 * 60 * 1000 * 1000;//这里执行的是int型的运算,再把结果转为long,有溢出
final long MILLIS_PER_DAY = 24 * 60 * 60 * 1000;
System.out.println(MICROS_PER_DAY / MILLIS_PER_DAY);

x += i;与x = x + i;不一定等价
The Java language specification says that the compound assignment E1 op= E2 is equivalent to the simple assignment E1 = (T) ((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once
数组的toString()方法
String letters = "ABC";char[] numbers = { '1', '2', '3' };System.out.println(letters + " easy as " + numbers);

String a = "abc.efg";
a=a.replaceAll(".","/");//正则表达式
System.out.println(a);

java中有lebel,虽然不能用goto
System.out.print("iexplore:");
http://www.google.com;
System.out.println(":maximize");//乃合法程序

//死循环
public static final int END = Integer.MAX_VALUE;
public static final int START = END - 100;
public static void main(String[] args) {
int count = 0;
for (int i = START; i <= END; i++)
count++;
System.out.println(count);
}

//浮点数的不精确性
final int START = 2000000000;
int count = 0;
for (float f = START; f < START + 50; f++)
count++;
System.out.println(count);//输出0

there is no dynamic dispatch on static methods //C++也是这样

 the instanceof operator is defined to return false when its left operand is null
the instanceof operator requires that if both operands are class types, one must be a subtype of the other

qualifying expression for a static method invocation is evaluated, but its value is ignored。eg:((Null) null).greet();

A local variable declaration can appear only as a statement directly within a block
for (int i = 0; i < 100; i++)
  String x = new String();//编译错误

there is no int value that represents the negation of Integer.MIN_VALUE and no long value that represents the negation of Long.MIN_VALUE。So  Math.abs is not guaranteed to return a nonnegative result。

hack.TypeIt.ClickIt.printMessage overrides click.CodeTalk.printMessage
package hack;

import click.CodeTalk;
public class TypeIt {
    private static class ClickIt extends CodeTalk {
        void printMessage() {
            System.out.println("Hack");
       }
    }
    public static void main(String[] args) {
        ClickIt clickit = new ClickIt();
        clickit.doIt();
    }
}


package click;
public class CodeTalk {
    public void doIt() {
        printMessage();
    }
    void printMessage() {
        System.out.println("Click");
    }
}

Converting an int or a long value to float, or a long value to double can result in loss of precision.



原创粉丝点击