开发者

How often will a function be called in a ternary operator?

I have this 开发者_开发问答line of Java code:

return getValue() != null ? getValue() : 0

How often will getValue be executed? Once or twice?

EDIT: If this is compiler-dependant, I'm especially interested in the compiler from the Sun JDK.


if getValue() == null - once

if getValue() != null - twice


only once if getValue() returns null, twice if the first time returned something other than null.


If getValue() returns a non-null value, twice.

public class Test {
public static void main(String[] args) {
    Test t = new Test();
    boolean x = t.doSomething()? t.doSomething():false;
}
public boolean doSomething(){
    System.out.println("calling doSomething");
    return true;
}
}

output:

calling doSomething
calling doSomething


Cleared answer:

From a developer perspective:

if getValue() == null - Will be called once

if getValue() != null - Will be called twice

From the JIT-Compiler perspective:

Depends on the compiler and your method. It will be at most called 2 times and at least 0 times.

  • Two times if not null; the compiler doesn't optimize; or the method has side effects
  • Zero times if first call to getValue() ALWAYS return null and has no side effects and the compiler does that optimization


Could you re-write it? I'm not familiar with Java, but in C++ you could say

return (x=getvalue()) != null ? x : 0

And if that wouldn't work in Java, could you move the assignment before the return? Does it need to be a single line?

x = getvalue();
return x != null ? x : 0

John C>


I have a different scenario that is related to your question. I also want to set a value to a variable that is a result of the ternary operator like this:

String thing = something == null ? "the other thing" : getSomethingElse();

That code still executes "getSomethingElse()" even if "something" is null.

It seems that all the functions within a ternary operator get executed before the evaluation of the condition---contrary to answers given by others.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜