【问题标题】:what is the difference between method(String str) and method(Final String str) [duplicate]方法(String str)和方法(Final String str)有什么区别[重复]
【发布时间】:2015-02-16 01:17:41
【问题描述】:

在方法参数中使用 Final 关键字让我感到困惑

public void helloWorld(String str)
{

}


public void helloWorld(Final String str)
{

}

What is the differences between them?

【问题讨论】:

    标签: java methods arguments keyword


    【解决方案1】:

    public void helloWorld(final String str) 不允许你在方法内部本地更改str 的值,而没有 final 关键字,你可以在本地更改它。

    public void helloWorld(String str)
    {
         str = "something"; // OK
    }
    
    
    public void helloWorld(final String str)
    {
        str = "something"; // ERROR
    }
    

    当然,即使helloWorld(String str) 也无法更改传递给方法的String 的值,因为Java 是一种按值传递的语言。

    【讨论】:

    • 还有 int 或任何其他数据类型。
    • @BelieveToLive 对于int 和任何其他数据类型,答案都是一样的。
    猜你喜欢
    • 2011-04-21
    • 2022-01-23
    • 2012-09-26
    • 1970-01-01
    • 2017-02-18
    • 2018-07-28
    相关资源
    最近更新 更多