title: Java Scope: Returning an object instantiated inside a method - Is it dangerous?
body: <p>I'm a student in Java class and learned something about Java today that made my gears turn. When I asked the teacher how and why, he wasn't sure about the behavior. Can anyone explain why the following example works?</p>
  
  <pre><code>class Example {
      public int ex_val;
  
      public Example (int a) {
          this.ex_val = a;
      }
  
      public int getExVal () {
          return this.ex_val;
      }
  }
  </code></pre>
  
  <p>If I were to create an instance of "Example" inside a method of another class and "return" the object, it can successfully make the jump out of it's original scope and be used subsequently.</p>
  
  <pre><code>class ParentObject {
      // Instance Variables    
      public Example a;
  
      public ParentObject (int number) {
          // Initialize instance variable object from out-of-scope instantiation
          this.a = genExample(number);
  
          // Verify scope creep
          System.out.println(this.a.getExVal());
      }
  
      public Example genExample (int a) {
          return new Example(a);
      }
  }
  </code></pre>
  
  <p>This DOES work, but is this behavior stable? Can I count on this? Can the garbage collector jump in between the return statement of one method and assignment statement of the calling function? Am I running the risk of failure based on my OS's version of the JVM? This seems like handy functionality if it can be relied upon.</p>