简体   繁体   中英

How does Java know when a void method has finished its method body?

Let's say I have some code:

public int doSomething(int x)
{
    otherMethod(x);
    System.out.println("otherMethod is complete.");
    return 0;
}

public void otherMethod(int y)
{
    //method body
}

Since otherMethod's return type is void, how does the doSomething method know when otherMethod has completed, so it can go to the next like and print " otherMethod is complete."?

EDIT: Added return 0; to doSomething method so the example code will compile.

The parser knows where the end of execution is and even adds a return, for example:

 public static void main(String args[])  {

}

compiles to:

 public static main([Ljava/lang/String;)V
   L0
    LINENUMBER 34 L0
    RETURN <------ SEE?
   L1
    LOCALVARIABLE args [Ljava/lang/String; L0 L1 0
    MAXSTACK = 0
    MAXLOCALS = 1
}

And the same applies to your code (though I've added in the return 0 since your code doesn't compile):

 public int doSomething(int x)
    {
        otherMethod(x);
        System.out.println("otherMethod is complete.");
        return 0;
    }

    public void otherMethod(int y)
    {
        //method body
    }

compiled code:

public doSomething(I)I
   L0
    LINENUMBER 38 L0
    ALOAD 0
    ILOAD 1
    INVOKEVIRTUAL TestRunner.otherMethod (I)V
   L1
    LINENUMBER 39 L1
    GETSTATIC java/lang/System.out : Ljava/io/PrintStream;
    LDC "otherMethod is complete."
    INVOKEVIRTUAL java/io/PrintStream.println (Ljava/lang/String;)V
   L2
    LINENUMBER 40 L2
    ICONST_0
    IRETURN
   L3
    LOCALVARIABLE this LTestRunner; L0 L3 0
    LOCALVARIABLE x I L0 L3 1
    MAXSTACK = 2
    MAXLOCALS = 2

  // access flags 0x1
  public otherMethod(I)V
   L0
    LINENUMBER 46 L0
    RETURN <-- return inserted!
   L1
    LOCALVARIABLE this LTestRunner; L0 L1 0
    LOCALVARIABLE y I L0 L1 1
    MAXSTACK = 0
    MAXLOCALS = 2
}

Because of the ending bracket. Once the thread gets to the end of the method, it will return. Additionally, the programmer can specify when a void method is finished by writing return;

Edit: I got the question mixed up. The Thread executes one method at a time, one statement at a time, so once the thread is finished a method it will go to the next line in the calling method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM