Java的finally是否一定会执行?
try {
return 1;
} catch (Exception ex) {
//...
} finally {
//...
return 2;
}
类似“try里的return语句会不会使得finally块被跳过”或者“到底是return 1还是return 2”之类的问题常常会在面试时被问到。 这篇Oracle的文档给出了答案,
The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break.
意思是return
之类的关键字不会使得finally块的执行被跳过。
除非在执行try时JVM退出了(比如调用了System.exit()
);或者执行try的线程被中断或者杀死了。
If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
Bit Twiddling Hacks
Java的Integer
类有个highestOneBit
方法,可以返回一个整数的二进制表示的最左边的1
的位置。
public static int highestOneBit(int i) {
// HD, Figure 3-1
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
return i - (i >>> 1);
}
那么上面的实现到底是在干什么?!😨
Integer
类的Javadoc上说highestOneBit
的实现参考自书籍Hacker’s Delight。
Implementation note: The implementations of the “bit twiddling” methods (such as highestOneBit and numberOfTrailingZeros) are based on material from Henry S. Warren, Jr.’s Hacker’s Delight, (Addison Wesley, 2002).
或许面试前可以看看这边书,让面试官惊讶一下。
另外,google一下“Bit Twiddling Hacks”,也可以发现很多参考资料。比如这篇pdf,以及这个网站。
Java支持的位操作运算有:~
,&
,^
,|
,<<
,>>
,>>>
。
The unsigned right shift operator “»>” shifts a zero into the leftmost position, while the leftmost position after “»” depends on sign extension.
>>>
会在最左边补0
;>>
运算后,最左边是0
还是1
取决于整数的正负号。