title: Does Java optimize away a field that's just serving as a return value?
body: <p><strong>Why I'm asking:</strong></p>
  
  <p>I wanted to know it there is any optimization going on at the compiler side that would make one or the other method to return preferable. Since I have read <a href="https://stackoverflow.com/questions/43390869/does-python-optimize-away-a-variable-thats-only-used-as-a-return-value">this post</a> that python does not optimize the method to run faster.</p>
  
  <p><strong>The example:</strong></p>
  
  <p>I've declared 2 methods that deliver the same value. But <code>barA</code> returns it via an internal field declaration. </p>
  
  <pre><code>public class Foo {
      public int barA(){
          int a = 1;
          return a;
      }
  
      public int barB(){
          return 1;
      }
  }
  </code></pre>
  
  <p><strong>The tests:</strong></p>
  
  <pre><code>public class TestFoo {
      Foo foo = new Foo();
      Method methodA = foo.getClass().getMethod("barA");
      Method methodB = foo.getClass().getMethod("barB");
  
  
      public TestFoo() throws NoSuchMethodException {
      }
  
  
      @Test
      public void methodA() throws Exception {
          assertTrue(Integer.TYPE.equals(methodA.getReturnType()));
      }
  
      @Test
      public void methodB() throws Exception {
          assertTrue(Integer.TYPE.equals(methodB.getReturnType()));
      }
      @Test
      public void equalsSame() throws Exception{
          assertEquals(foo.barA(), foo.barB());
      }
  }
  </code></pre>
  
  <p><strong>The results:</strong></p>
  
  <p>The tests showed that I'm in fact dealing with the same value and return type in both methods.</p>
  
  <p><strong>Disclaimer:</strong>
  This picture is not meant to highlight the stop watch, junit runs for each method, as it's in no way linked to the compiler optimization I'm asking about.</p>
  
  <p><a href="https://i.stack.imgur.com/I8NFZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I8NFZ.png" alt="The tests"></a></p>
  
  <p><strong>The question:</strong></p>
  
  <p>Does Java actually try to optimize away "useless" field declarations in order to execute faster?</p>
  
  <p>I was not able to find a question addressing this.</p>
  
  <p><strong>Using:</strong></p>
  
  <ul>
  <li>jdk 1.8.0_121</li>
  <li>junit 4.10</li>
  </ul>