A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© H-Deka 中级黑马   /  2014-3-27 18:09  /  1156 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 H-Deka 于 2014-3-28 10:29 编辑

结果为什么是55,try中的return不是代表结束了吗?




public class Test
{
public static void main(String args[])
{
Test t = new Test();
int b = t.get();
System.out.println(b);
}
public int get()
{
try
{
return 33 ;
}
finally
{
return 55 ;
}
}
}

评分

参与人数 1技术分 +1 收起 理由
ily521125 + 1

查看全部评分

5 个回复

倒序浏览
  1. public class Test
  2. {
  3.         public static void main(String args[])
  4.         {
  5.                 Test t = new Test();
  6.                 int b = t.get();   //这里拿到的必然是最后return的55
  7.                 System.out.println(b);
  8.         }
  9.         public int get()
  10.         {
  11.                 try
  12.                 {
  13.                         return 33 ;
  14.                 }
  15.                 finally   //所谓finally就是无论前面是否执行,finally的方法一定是会执行的,从单词词义也看的出
  16.                 {
  17.                         return 55 ;
  18.                 }
  19.         }
  20. }
复制代码


注释了,看下

评分

参与人数 1技术分 +1 收起 理由
ily521125 + 1

查看全部评分

回复 使用道具 举报
楼主要是不明白的话,可以做个测试。。
在try中写了return,后面又写了finally,
* 是先执行return还是先执行fianlly?
* @author hjl
*
*答:是先执行return

  1. public class test6 {

  2.         public static int test(){
  3.                 try {
  4.                         return function1();
  5.                 }finally{
  6.                         return function2();
  7.                 }
  8.         }
  9.         public static int function1(){
  10.                 System.out.println("function1执行了");
  11.                 return 1;
  12.         }
  13.         public static int  function2(){
  14.                 System.out.println("function2执行了");
  15.                 return 2;
  16.         }
  17.        
  18.         public  static void main(String[] args){
  19.                 System.out.println(new test6().test());
  20.         }
  21. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
ily521125 + 1

查看全部评分

回复 使用道具 举报
代码的执行过程分析:
  1. package cn.itcast;

  2. public class Test{
  3.         public static void main(String args[]) {
  4.                 Test t = new Test();
  5.                 int b = t.get(); //step1:对象t调用get()方法,
  6.                                  //step4:将返回值55赋给b;
  7.                 System.out.println(b);//step5:将b的值55打印到控制台;
  8.         }

  9.         public int get() {
  10.                 try {
  11.                         return 33 ;//step2:执行try{}内的return33;
  12.                 }
  13.                 finally {
  14.                         return 55 ;//step3:执行finally{}内的return55;
  15.                 }
  16.         }
  17. }
复制代码

所以结果是55,希望对你有帮助!

评分

参与人数 1技术分 +1 收起 理由
ily521125 + 1

查看全部评分

回复 使用道具 举报
finally里里的语句一定会执行,除非在try中有语句  System.exit(0);  所以返回的语句肯定是55了
回复 使用道具 举报
因为finally内的代码一定会被执行,那么返回的便是55
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马