Possible Duplicate:
what happens to an object in Java if you do not reference it, like here : myString.concat(“that”)
public class ReturnTest
{
public static void main(String[] args)
{
ReturnTest rt = new ReturnTest();
rt.show();
}
public String show()
{
return "Hello";
}
}
In the above code the show()
method returns a String
value which is not captured by any variable. Neither the compiler nor the JVM raise any warning, error or exception whatsoever. The same is true for primitive return types. Why?
Shouldn't the compiler make sure that no important value returned by a method is lost by this?
How can i fix this from a shell??
Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so.
If no return statement appears in a function definition, control automatically returns to the calling function after the last statement of the called function is executed. In this case, the return value of the called function is undefined.
The type of the expression in the return statement must match the return type of the method. When you declare that the return type is double , you are making a promise that this method will eventually produce a double value.
A method does not have to return something, but all methods need to have a return type. The return type tells Java what type of value it can expect the method to return, the void type is just there to tell Java that the method does in fact not return anything.
This is the design of the language.
In many cases, methods returns a value you don't care about. For example StringBuilder.append()
returns the object itself.
It is true that in some cases an important return value might be lost. For example, InputStream.skip(long n)
returns the number of bytes skipped. And read
returns the number of bytes read. There are some tools (Checkstyle, FindBugs) that detect such bugs. But the language itself doesn't request checking the return value. And even if it did, the program could choose to ignore the value.
You can annotate a method with @CheckReturnValue
if its return value should always be used. Static code analysis like FindBugs consider this annotation and raise warning when you violate it.
At least this is very reasonable when the method returns some kind of object that needs final processing at the end where the caller is responsible for. This is true for resources that must be closed at the end. Locks that must be released at the end ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With