10.10 Expressions as Statements

Some expressions can be turned into statements by adding a semicolon to the end. To skip an element in an Enumeration, one might execute this statement:

 e.nextElement();          // Throw away what's returned 

This is a statement consisting of the expression e.nextElement(). The expression returns a value of type Object. The statement compiles to

 .var 1 is e Ljava/util/Enumeration; aload_1                                     ; Push e invokeinterface java/util/Enumeration/nextElement                 ()Ljava/lang/Object; 1      ; Call the method,                                             ; leaving the result                                             ; on the stack pop                                         ; Remove the result 

The pop is necessary to ensure that the stack is empty after executing the expression.

It is actually pretty rare that a pop must be included explicitly. Usually, when a method returns a value, it is used as part of another statement or expression that needs the value. The code for the enclosing statement or expression has the responsibility for removing the result of the subexpression.

When the result of a method call is void, it isn't necessary to remove the value returned from the method. That's because the method does not really return a value. We have seen this code compiled many times before in this book:

 System.out.println("Hello, world"); 

The println method returns void, so there is no pop included after the method call.

Programming for the Java Virtual Machine
Programming for the Javaв„ў Virtual Machine
ISBN: 0201309726
EAN: 2147483647
Year: 1998
Pages: 158
Authors: Joshua Engel

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net