为什么不需要将方法的返回值赋给变量? [英] Why isn't it necessary to assign a method's return value to a variable?

查看:95
本文介绍了为什么不需要将方法的返回值赋给变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:





public class ReturnTest
{
    public static void main(String[] args)
    {
        ReturnTest rt = new ReturnTest();
        rt.show();
    }

    public String show()
    {
        return "Hello";
    }
}

在上面的代码中, show()方法返回一个不被任何变量捕获的 String 值。编译器和JVM都不会引发任何警告,错误或异常。原始返回类型也是如此。为什么?

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?

如何从shell中解决这个问题?

How can i fix this from a shell??

推荐答案

这是语言的设计。

在许多情况下,方法返回一个不关心的值。例如 StringBuilder.append()返回对象本身。

In many cases, methods returns a value you don't care about. For example StringBuilder.append() returns the object itself.

确实,在某些情况下,重要的返回价值可能会丢失。例如, InputStream.skip(long n)返回跳过的字节数。而读取返回读取的字节数。有一些工具( Checkstyle FindBugs )来检测这些错误。但是语言本身并不要求检查返回值。即使是这样,程序也可以选择忽略该值。

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.

这篇关于为什么不需要将方法的返回值赋给变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆