Finally frequently asked questions during the interview

Written examination is common

public class FinallyDemo {
	public static void main(String[] args) {
		System.out.println(
				test("0")+","+test(null)+","+test("")
				);
	}
	public static int test (String str) {
		try {
			return str.charAt(0)-'0';
		}catch (NullPointerException e) {
			return 1;
		} catch (Exception e) {
			return 2;
		}
	}
}

Result: 0,1,2

package exception;
/**
 * 面试中finally常见问题
 * @author Lemon
 */
public class FinallyDemo3 {
	public static void main(String[] args) {
		System.out.println(
				test("0")+","+test(null)+","+test("")
				);
	}
	public static int test (String str) {
		try {
			return str.charAt(0)-'0';
		}catch (NullPointerException e) {
			return 1;
		} catch (Exception e) {
			return 2;
		}finally {//如果加finally最后结果会是3,3,3
			return 3;
		}
	}
}

Result: 3,3,3,

Please specify final, finally, finalize separately

final means final and unchangeable. Used to modify classes, methods and variables. When modifying the class, it cannot be inherited, the modification method cannot be rewritten, and the variable needs to be initialized and cannot be assigned twice.
Finally, it is part of the exception handling. It can only be used in the try/catch statement to indicate the hope that the statement in the finally block The code must be executed at the end. So in the code logic that needs to be executed no matter what happens, it can be placed in the finally block. Common such as resource release.
finalizefinalize is a method defined by object. This method is called when the GC releases the resource of the object. The object is released after the call.
Note: If this method is rewritten, there should be no time-consuming operations in it. (Prevent from affecting GC work)

Guess you like

Origin blog.csdn.net/qq_37669050/article/details/98030292