10.13 Returns

A return statement in Java translates into one of the six instructions: areturn, ireturn, freturn, dreturn, lreturn, or return. The instruction chosen depends on the return type of the method.

The simplest case is where the return type of the method is void:

 public static void main(String a[]) {    System.out.println("Hello, world");    return; } 

The return statement translates simply into a return instruction. No arguments are required. The full compilation of this method is

 .method public static main([Ljava/lang/String;)V ; System.out.println("Hello, world"); getstatic java/lang/System/out Ljava/io/PrintStream; ldc "Hello, world" invokevirtual java/io/PrintStream(Ljava/lang/String;)V ; return; return .end method 

At the end of a void method, if no return statement is given, the Java compiler assumes one. Thus, this code would compile the same way even if the return statement were omitted. This is possible only because there is no return value.

If the return type is not void, then the return statement must include an expression that evaluates to the value to return. The type of that expression must conform to the return type of the method. For example,

 float five() {    return 5; } 

Because the declared return type of this method is float, the return type must be freturn. The expression 5 is an int, but it can be automatically promoted to a float. The return statement compiles into an evaluation of the expression, followed by a cast, followed by the appropriate returning instruction:

 .method five()F iconst_5                   ; Push the constant 5 i2f                        ; Automatic promotion to float freturn                    ; Return that value .end method 

As with arithmetic expressions, only promotions are considered, not demotions. This is illegal:

 int six() {    return 6.0;             // ILLEGAL! Can't automatically                            // convert float to int } 

If the return type is an object type, then an areturn instruction is used. The compile-time type of the expression must be a subtype of the return type of the method. For example,

 Object name() {    return "Murray"; } 

returns a String where an Object is expected. This is legal, because a String is an Object. This method compiles as

 .method name()Ljava/lang/String; ldc "Murray" areturn .end method 

The generated code is acceptable to the verification algorithm, because the stack contains a java/lang/String when the areturn instruction is executed. This meets the requirements for an areturn.



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