参考答案
try 和 finally 至少一个语句块包含 return 语句的情况:
- finally 没有 return,finally 对 return 变量的重新赋值修改无效;
- finally 语句块会执行;
- try 和 finally 都包含 return,return 值以 finally 语句块 return 值为准。
实例:
public static void main(String[] args) { System.out.println(getString()); } public static String getString() { String str = "A"; try { str = "B"; return str; } finally { System.out.println("finally change return string to C"); str = "C"; } }
结果:
finally change return string to C B
finally 语句块中,新增 return 语句:
public static void main(String[] args) { System.out.println(getString()); } public static String getString() { String str = "A"; try { str = "B"; return str; } finally { System.out.println("finally change return string to C"); str = "C"; return str; } }
结果:
finally change return string to C C
以上,是Java面试题【return与finally的执行顺序,对返回值的影响】的参考答案。
输出,是最好的学习方法。
欢迎在评论区留下你的问题、笔记或知识点补充~
—end—