【发布时间】:2015-02-05 23:28:57
【问题描述】:
我正在寻找在 if 条件下启动变量的可能性,所以它只在条件范围内有效。
例子:我想改变这个:
String tmp;
if ((tmp = functionWithALotOfProcessingTime()) != null)
{
// tmp is valid in this scope
// do something with tmp
}
// tmp is valid here too
变成类似这样的东西:
if ((String tmp = functionWithALotOfProcessingTime()) != null)
{
// tmp is *ONLY* in this scope valid
// do something with tmp
}
【问题讨论】:
-
Java 的作用域规则不是这样定义的。
-
编译器会自动将变量的作用域限制在它被使用的地方。顺便说一句,这对性能没有影响,只是将变量的使用限制在预期使用的地方。
-
本题不涉及性能问题。
标签: java performance if-statement conditional-statements