Note that there are some explanatory texts on larger screens.

plurals
  1. POModifying a return value of a method in a finally block doesn't return the actual modified value
    text
    copied!<p>As a rule, the <code>finally</code> block is always executed whether or not an exception is thrown in the <code>try</code> block or a <code>continue</code>, <code>break</code> or <code>return</code> statement encounters in the <code>try</code> block itself.</p> <p>Accordingly, the return value of the method in the code snippet given below should be changed but it doesn't.</p> <pre><code>final class Product { private String productName=null; public Product(String productName) { this.productName=productName; } public String getProductName() { try { return this.productName; } finally { this.productName="The product name has been modified in the finally block."; System.out.println("Product name in the finally block : "+this.productName); } } } public final class Test { public static void main(String...args) { System.out.println(new Product("Intel core i3").getProductName()); } } </code></pre> <p>The method <code>getProductName()</code> simply returns the product name which is assigned by the constructor to the field <code>productName</code> before this method is invoked.</p> <p>Before this method returns, the value of <code>productName</code> is modified in the <code>finally</code> block. Therefore, the method should return this new modified value but it returns the initial value which is assigned to <code>productName</code> when an instance of this class has been constructed.</p> <hr> <p>It produces the following output:</p> <blockquote> <p>Product name in the finally block : The product name has been modified in the finally block.<br> Intel core i3</p> </blockquote> <p>Why doesn't this method return the new value which is assigned to the <code>productName</code> field in the <code>finally</code> block? It should return the new value. Shouldn't it?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload