Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ternary Operator - JAVA [duplicate]

Is it possible to change this:

if(String!= null) {      callFunction(parameters);  } else {      // Intentionally left blank  } 

...to a ternary operator?

like image 248
Lucas Pugliese Avatar asked Aug 06 '14 14:08

Lucas Pugliese


People also ask

What is ?: In Java?

The ternary conditional operator ?: allows us to define expressions in Java. It's a condensed form of the if-else statement that also returns a value.

Is ternary better than if-else?

If the condition is short and the true/false parts are short then a ternary operator is fine, but anything longer tends to be better in an if/else statement (in my opinion). Save this answer.

Is it good to use ternary operator in Java?

Overall, you should only use ternary statements when the resulting statement is short. Otherwise, write a normal if statement. The purpose of a ternary operator is to make your code more concise and readable. Moving a complex if statement into a ternary operator goes against that goal.

Is ternary operator faster than if Java?

Yes! The second is vastly more readable.


1 Answers

Well, the ternary operator in Java acts like this...

return_value = (true-false condition) ? (if true expression) : (if false expression); 

...Another way of looking at it...

return_value = (true-false condition)               ? (if true expression)               : (if false expression); 

You question is kind of vague and we have to assume here.

  • If (and only if) callFunction(...) declares a non-void return value (Object, String, int, double, etc..) - it seems like it does not do that via your code - then you could do this...

    return_value = (string != null)               ? (callFunction(...))               : (null); 
  • If callFunction(...) does not return a value, then you cannot use the ternary operator! Simple as that. You will be using something that you don't need.

    • Please post more code to clear up any issues

Nonetheless, ternary operator should represent alternative assignments only!! Your code does not seem to do that, so you should not be doing that.

This is how they should work...

if (obj != null) {            // If-else statement      retVal = obj.getValue();  // One alternative assignment for retVal  } else {      retVal = "";              // Second alternative assignment for retVale  } 

This can be converted to...

retVal = (obj != null)        ? (obj.getValue())        : (""); 

Since it seems like you might be trying to just refactor this code to be a one-liner, I have added the following

Also, if your false-clause is truely empty, then you can do this...

if (string != null) {      callFunction(...);  } // Take note that there is not false clause because it isn't needed 

OR

if (string != null) callFunction(...);  // One-liner 
like image 113
Christopher Rucinski Avatar answered Sep 28 '22 21:09

Christopher Rucinski