黑马程序员技术交流社区

标题: 感觉还不错的题目,可以看看! [打印本页]

作者: 余银桂    时间: 2012-6-18 19:13
标题: 感觉还不错的题目,可以看看!
  1. //题目一
  2. public class TryCatch {

  3.         public static void main(String[] args) {
  4.                 System.out.println("main "+new TryCatch().test());
  5.         }
  6.         
  7.         public int test(){
  8.                 int i = 1;
  9.         try
  10.         {
  11.                 i = 55555;
  12.                    return i;
  13.         } catch(Exception e) {
  14.                 return i;
  15.         }
  16.         
  17.         finally
  18.         {
  19.             i = 1000;
  20.             
  21.            
  22.         }

  23.         }
  24. }
复制代码
  1. //题目二

  2. public class TryCatch {

  3.         public static void main(String[] args) {
  4.                 System.out.println("main "+new TryCatch().test());
  5.         }
  6.         
  7.         public int test(){
  8.                 int i = 1;
  9.         try
  10.         {
  11.                 i = 55555;
  12.                    return i;
  13.         } catch(Exception e) {
  14.                 return i;
  15.         }
  16.         
  17.         finally
  18.         {
  19.             i = 1000;
  20.             return i;
  21.             
  22.            
  23.         }

  24.         }
  25. }




  26. //尝试一下一眼看过去 你认为的答案是什么,然后运行验证一下
复制代码

作者: 胡大强    时间: 2012-6-18 19:25
输出 main 55555.。。楼主要说明说明问题呢?
作者: 余银桂    时间: 2012-6-18 19:56
胡大强 发表于 2012-6-18 19:25
输出 main 55555.。。楼主要说明说明问题呢?

2个都是么?
作者: 王晓新    时间: 2012-6-18 20:02
余银桂 发表于 2012-6-18 19:56
2个都是么?

你定义的test()方法的返回类型是int型,第一个finally执行了但是没有return i,所以打印的还是main 5555
第二个执行了finally后将i=1000返回给main方法打印出来了、finally是必须执行的。
作者: 马林康    时间: 2012-6-18 20:29
mark           
作者: 马林康    时间: 2012-6-18 20:29
mark                        
作者: 黑马-王言龙    时间: 2012-6-18 20:59
还好全中




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2