tuntun wretee
tuntun wretee

Reputation: 49

conditional operator usage in the below code

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.

Upvotes: 0

Views: 97

Answers (4)

Siva
Siva

Reputation: 1940

1. Now I want that if a.active is true and b.active is also true then
    the result should be Active

boolean status = a.isActive() && b.isActive();
String value = status ? "Active" : "Inactive";

2. if initially a.active fails then no need to test b.isactive

Java follows Short circuit Evaluation So you no need to care about that java will automatically do that

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

For the purpose of readability, you could to wrap the condition

a.isActive() && b.isActive() 

in circular brackets ():

(a.isActive() && b.isActive())

Also there is no need of bracket at the end. So your final condition should look like:

(a.isActive() && b.isActive()) ? "Active" : "NotActive";

As the brackets are optional so the condition can be re-written as:

a.isActive() && b.isActive() ? "Active" : "NotActive";

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500185

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:

  • I wouldn't use the brackets. They're unnecessary. You're not calling a method - it's just a conditional operator.
  • I'd rename the variable to accessType. Java naming conventions use camelCase for variables.

So:

String accessType = a.isActive() && b.isActive() ? "Active" : "NotActive";

Upvotes: 3

newuser
newuser

Reputation: 8466

Take a look condional Operator

   boolean isAActive = a.isActive();
   boolean isBActive = b.isActive();
   String AccessType = (isAActive && isBActive) ? "Active" : "NotActive";

instead of

String AccessType = (a.isActive() && b.isActive() ? "Active" : "NotActive");

use the conditions with in the bracket

Upvotes: 0

Related Questions