I've seen the ternary operator can be used in if else situations but neither of them included a else if(if-else ladder).So,is there a way to use ternary operator in that situation. I'm new to the java. So doesn't mind if it's silly question.
Can ternary operator be used in if else ladder in java?
1.5k Views Asked by R. S. D AtThere are 4 best solutions below
On
Lets take an example for what you are suggesting:
Normal code:
int greatestNumber(int a, int b, int c)
{
if(a > b && a > c)
{
return a;
}
else if(b > a)
{
if(b > c)
{
return b;
}
else
{
return c;
}
}
return 0;
}
Same code but with Ternary operator:
int greatestNumber(int a, int b, int c)
{
return (a > b && a > c)? a: (b > a? (b > c? b: c): 0);
}
As you can see it is possible but not recommended as it creates code that is difficult to read
On
Either cascading if-else or nested ternary operations can be considered. Lots of folks prefer cascading if-else statements. I've found nested ternary operations to be acceptable, so long as the expressions are simple and adequate formatting is used.
What will matter is how readable is the resulting code. For nested ternary operations, formatting and properly placed parenthesis are important.
Here are two examples:
public int selectorI(boolean c1, int v1, boolean c2, int v2, boolean c3, int v3, int vDef) {
if ( c1 ) {
return v1;
} else if ( c2 ) {
return v2;
} else if ( c3 ) {
return v3;
} else {
return vDef;
}
}
public int selectorT(boolean c1, int v1, boolean c2, int v2, boolean c3, int v3, int vDef) {
return ( c1 ? v1 :
( c2 ? v2 :
( c3 ? v3 : vDef ) ) );
}
On
Proper formatting styles:
Sample 1:
return c1 ? v1
: c2 ? v2
: c3 ? v3
: v4;
Sample 2:
return c1 ? v1 :
c2 ? v2 :
c3 ? v3 :
v4; // or on previous line
One reason to use a ternary expression is to only assign a variable once, where you would otherwise be forced to extract a method (with multiple returns).
String type = c instanceof String ? "Text"
: c instanceof Number ? "Numeric"
: "Something else";
It's very close to the switch expressions we're waiting for but available now.
Yes, but it's consider a code smell according to sonar
For example continuing checking a after
:Should be according to sonar