I was using the conditional operator as shown below..
String AccessType = (a.isActive() && b.isActive() ? "Active" : "NotActive");
Now I want that if a.active is true and b.active is also true then the result should be Active but if initially a.active fails then npo need to test b.isactive just print Not active now please advise does my above implementation is correct or not.
Your implementation is already correct. The "laziness" aspect (only calling b.isActive()
if a.isActive()
returns true) is taken care of by the behaviour of the &&
operator, which is short-circuiting.
From section 15.23 of the JLS:
The conditional-and operator && is like & (ยง15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true.
The fact that you're using this as the condition (first operand) of the conditional operator is irrelevant. So your code is equivalent to:
boolean active = a.isActive() && b.isActive();
String AccessType = (active ? "Active" : "NotActive");
I would make two changes to your code though:
accessType
. Java naming conventions use camelCase
for variables.So:
String accessType = a.isActive() && b.isActive() ? "Active" : "NotActive";
See more on this question at Stackoverflow