How does Java know when the void method completed its method?

Say I have a code:

public int doSomething(int x) { otherMethod(x); System.out.println("otherMethod is complete."); return 0; } public void otherMethod(int y) { //method body } 

Since the return type of otherMethod is not valid, how does the doSomething method know when otherMethod completed, so it can go to the next character and print " otherMethod complete." ??

EDIT: added return 0; to doSomething, so the sample code will be compiled.

+7
source share
2 answers

The analyzer knows where execution ends and even adds a return, for example:

  public static void main(String args[]) { } 

compiles:

  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 (although I added 0 in the opposite, since your code does not 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 } 
+14
source

Due to the end brace. Once the thread reaches the end of the method, it will return. In addition, the programmer can indicate when the void method is completed by writing return;

Edit: my question is messed up. The thread executes one method at a time, one statement at a time, so as soon as the thread completes the method, it will go to the next line in the calling method.

+1
source

All Articles