title: Java Optional working of orElse is not as if else
body: <p>In Optional while optional.orElse method is call, irrespective of the element is present or not the orElse part is executed it does not behave as the if else condition.</p>
  <p>In the below code if you see in <strong>Case 1</strong> both getNullPoJo and getDefaultPoJo is executed since getNullPoJo will return empty Optional</p>
  <p>In <strong>Case 2</strong> where you will get a Optional with loaded value (from getLoadedPoJo) also you getDefaultPoJo is executed</p>
  <p>I am just trying to understand the working of optional.orElse.</p>
  <pre><code>public static void main (String [] a) {
      PoJo poJo1=getNullPoJo().orElse(getDefaultPoJo());//Case 1
      System.out.println(&quot;pojo1 Got &quot;+poJo1.getVariable());
      PoJo poJo2=getLoadedPoJo().orElse(getDefaultPoJo());//Case 2
      System.out.println(&quot;pojo2 Got &quot;+poJo2.getVariable());
  }
  
  private static Optional&lt;PoJo&gt; getNullPoJo() {
      System.out.println(&quot;Executing getNullPoJo&quot;);
      Optional&lt;PoJo&gt; optional=Optional.empty();
      return optional;
  }
  
  private static Optional&lt;PoJo&gt; getLoadedPoJo() {
      System.out.println(&quot;Executing getLoadedPoJo&quot;);
      PoJo poJo =new PoJo();
      poJo.setVariable(&quot;Loaded&quot;);
      Optional&lt;PoJo&gt; optional=Optional.of(poJo);
      return optional;
  }
  
  private static PoJo getDefaultPoJo() {
      System.out.println(&quot;Executing getDefaultPoJo&quot;);
      PoJo poJo =new PoJo();
      poJo.setVariable(&quot;Default&quot;);
      return poJo;
  }
  </code></pre>
  <p><strong>The current Output is:</strong></p>
  <blockquote>
  <p>Executing getNullPoJo</p>
  <p>Executing getDefaultPoJo</p>
  <p>pojo1 Got Default</p>
  <p>Executing getLoadedPoJo</p>
  <p>Executing getDefaultPoJo</p>
  <p>pojo2 Got Loaded</p>
  </blockquote>
  <p><strong>My Expected Output is:</strong></p>
  <blockquote>
  <p>Executing getNullPoJo</p>
  <p>Executing getDefaultPoJo</p>
  <p>pojo1 Got Default</p>
  <p>Executing getLoadedPoJo</p>
  <p>pojo2 Got Loaded</p>
  </blockquote>
  <p>I do not want the call to getDefaultPoJo in <strong>Case 2</strong></p>