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.
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.
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.
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
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>