This question already has an answer here:
- Ternary Operators Java 6 answers
Is it possible to change this:
if(String!= null) {
callFunction(parameters);
} else {
// Intentionally left blank
}
...to a ternary operator?
This question already has an answer here:
Is it possible to change this:
if(String!= null) {
callFunction(parameters);
} else {
// Intentionally left blank
}
...to a ternary operator?
Well, the
ternary operator
in Java acts like this......Another way of looking at it...
You question is kind of vague and we have to assume here.
If (and only if)
callFunction(...)
declares anon-void
return value (Object
,String
,int
,double
, etc..) - it seems like it does not do that via your code - then you could do this...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.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...
This can be converted to...
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...
OR
It could be possible if your method
callFunction()
has a return type. Then, you could do it like SURESH ATTA wrote in his answer:Or with any other type for result or any other arguments. If you want to call a method in the
else
-Statement too, this one needs to have the same return type as the one in yourif
-statement.If your method doesn't have a return type / the return type of
callFunction()
isvoid
, it is not possible to change yourif
-else
-statement into a ternary operator.The ternary operator can be used to combine two expressions but an empty statement is not an expression.
A method invocation can be used as an expression if the method returns a value (read: is not declared
void
) and it could be used together with a dummy constantnull
to form a ternary operator but the result would be again an expression which is not allowed in places where a statement is required, in other words, it can not replace anif
statement.By adding another construct taking an expression and imposing no additional side effect you can construct a complete replacement. E.g. by declaring and assigning a new, otherwise unused, local variable you get:
But there is no benefit over simply saying
if(condition) callFunction(parameters);
. It might even add unnecessary overhead as it will perform auto-boxing if the return value is a primitive type.With Java 8 there is a solution to the puzzle that works even for
void
methods:but it still has no advantage over simply using
if
.Yes. You can with keeping same
null
inelse
block.Make sure that
callFunction(parameters)
return aString
.