java中变量的传递,传递“const” Java中的变量到方法

Is there an equivalent in Java to the passing on const references in C++?

Isn't leaving out the "constness" misleading in regard to the method signature?

解决方案

No, there isn't.

Java "final" is not an exact equivalent of C++ "const". The following (delayed initialization of a final variable) works in Java:

final double x;

int w = 1;

if (w > 2)

{

x = 0.5;

}

else

{

x = - 0.5;

}

but it doesn't work in C++ with "final" replaced by "const".

Using "final" on a variable in the method declaration can be useful in Java, because allows you to use this variable inside any anonymous class created inside your method.

PS. I was first disappointed by the lack of "const" in Java but later learned to live with "final".

PS2. The Java glossary (http://mindprod.com/jgloss/immutable.html) linked to in this thread has one thing wrong: no, you are not given a 100% guaranntee that the final variable doesn't change its value:

1) it changes from "undefined" to "defined", but the compiler will tell you if you reference it before initialization

2) on Linux, a double has 80-bit precision when stored in a register, but 64-bit when stored in memory. When a final double variable is pushed out of the register, it will be truncated and change its value. As Joel Spolsky says, "abstraction has sprung a leak".

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值