2014-04-04 329 views
-2

下面這段代碼的輸出是「Test Passed」;有人可以向我解釋爲什麼?將finally賦值給變量

public class Test { 
    public static void main(String args[]) { 
     System.out.println(new Test().print()); 
    } 

    protected StringBuilder print() { 
     StringBuilder builder = new StringBuilder(); 
     try { 
      builder.append("Test "); 
      return builder.append("Passed!!!"); 
     } finally { 
     builder = null; 
    } 
} 
+0

請使用代碼格式。 –

回答

0

答案很簡單。

Finally塊將肯定被執行,因爲不必返回從它的任何值,則try塊返回值將被傳遞到原主叫方

try { 
    builder.append("Test "); 
    return builder.append("Passed!!!"); 
} finally { 
    builder = null; 
} 

因此,你得到「測試通過! !」

代碼更改爲

StringBuilder builder = new StringBuilder(); 
try { 
    builder.append("Test "); 
    return builder.append("Passed!!!"); 
} finally { 
    return null; 
} 

肯定會打印出 「空」 如你預期

6

基本上,Java那樣如下:

StringBuilder valueToReturn = builder.append("Passed!!!"); 
executeFinallyBlock(); 
return valueToReturn; 

不管你在做內部在finally塊中,Java保留了對返回值的引用,並返回該引用。所以它變成:

StringBuilder valueToReturn = builder.append("Passed!!!"); 
builder = null; 
return valueToReturn;