refactoring if else to Single line conditional statement in Java? - java

I want to write single line if else check. But i am getting error.
Please help
if(x == 1) {
System.out.println("aaa");
}else {
System.out.println("bbb");
}
Is there a way to make above code as single like below. Getting compile error in below line
x == 1 ? System.out.println("aaa") : System.out.println("bbb");
Please help. I might be making a silly error i guess.

The second and third arguments of the conditional ternary expression must be expressions, so they can't be System.out.println("aaa").
Instead, so you can write:
System.out.println (x == 1 ? "aaa" : "bbb");
Now you have a ternary conditional expression that produces a value (either "aaa" or "bbb"), and that value is passed to System.out.println.

The ternary operator can only be used with expression returning a value. In your case, System.out.println("aaa") is not expression and can't be used.
You can use:
System.out.println(x == 1 ? "aaa" : "bbb");

Related

In java is ternary operator considered a single line expression while using inside a lambda function?

Collections.sort(employees, (employee1, employee2) -> {
return (employee1.getAge() >= employee2.getAge()) ? -1 : 1;
});
The above code sample sorts the 'employees' List according to age just fine. But, the code below gives an error.
Collections.sort(employees, (employee1, employee2) ->
employee1.getAge() >= employee2.getAge() ? -1 : 1;
);
Isn't the ternary operator considered as a single line expression?
The error shown is:
java: ')' expected;
java: illegal start of expression
Syntactically, the lambda body (the thing after ->) is either a block or an expression.
If it's a block, then it must contain zero or more statements. The return statement ends with a ;, which is why ; is needed in the first case.
In the second case, you attempted to write a conditional expression ("ternary operator"), but as you can see in the syntax, the trailing ; is not part of a conditional expression, (AFAIK, no expression ends with a ;) so you've written something extra that the parser didn't expect, which causes the code to not compile.
So you should delete the ;:
Collections.sort(employees, (employee1, employee2) ->
employee1.getAge() >= employee2.getAge() ? -1 : 1
);
Also, note that this implementation of Comparator does not ensure that sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y, which is part of the contract of Comparator.compare. sort will not work correctly.

Can we use '?' operator instead of nested-if condition?

A nested-if condition to be written using the ? : syntax. Is it not an allowed scenario?
Below is the code
int i=(10>5)?(2<5)?230:456;
System.out.println("i="+i);
Which I thought would be equal to
if(10>5){
if(2<5){
i=230;
}
else{
i=456;
}
}
My idea was that first 10>5 would be evaluated, and as it is true, it would then verify if 2<5 or not. Now since that is also true, "i" should be assigned to 230.
The error message was
ControlFlow.java:10: error: : expected
int i=(10>5)?(2<5)?230:456;
ControlFlow.java:10: error: ';' expected
int i=(10>5)?(2<5)?230:456;
^
ControlFlow.java:11: error: illegal start of expression
System.out.println("i="+i);
^
ControlFlow.java:11: error: ';' expected
System.out.println("i="+i);
You forgot to add a part of the expression. Try it as follows:
int i = (10>5) ? ( (2<5) ? 230:456 ) : 0;
Replace the above 0 to be the desired number you want your variable to be when your first condition (10>5) is false.
The ternary operator has the syntax
aBoolean ? value : value
and it will return a value itself, so you can nest them as
aBoolean ? (aBoolean ? value : value) : value
Your code (10>5)?(2<5)?230:456; however is equivalent to
aBoolean ? (aBoolean ? value : value)
so it is missing the second value for your first ternary operator.
Sometimes it may be easier to understand if you rearrange the conditions.
Instead of
int v = (a > b) ? (c > d) ? 100 : 200 : 300;
You can do
int v = (a <= b) ? 300 : (c > d) ? 100 : 200;
The only difference is in the latter case, the initial condition returns a value immediately when true and requires requires further evaluation when false.
Yes you can nest the ternary operator as deep as you can next the if conditions however, ternary operators being the condensed version of IF conditions, they can make ur code not readable if you condense them deeper.
Just remember to bracket the conditions just to make it readable but it's not a requirement (0<1) ?
You can go for below solutions. But this is not recommended today as Cognitive complexity of a source code is a considerable matter in industry today. According to the logic which you have shared the same can be implmented in both ways as below.
int i=(10>5) && (2<5)?230:456;
System.out.println("i="+i);
int i = (10>5)?(2<5)?230:456:0;
System.out.println("i="+i);

When would you use the conditional operator in java (? :) instead of the if else statement?

I have a piece of code that uses a conditional operator to compare the value of the variable x to 5:
(x >=5 ? x : -x)
What benefit is there to using a conditional operator over a regular if else statement?
Note that is ?: is an expression - it returns a value which must be consumed
z = (x >=5 ? x : -x)
The if construct in Java is not an expression (there are languages where it is) and does not return a value so in this sense they are not equivalent.
An example where they are equivalent is when the if options perform an assignment:
if("Cheese".equals(x)) {
type = "Dairy";
} else {
type = "Maybe not dairy";
}
this is the same as
type = "Cheese".equals(x) ? "Dairy" : "Maybe not dairy";
You can nest ?: to arbitrary depth but really shouldn't - it becomes quite difficult to read:
List<String> cheeses = Arrays.asList("Gouda", "Edam");
String x= "Gouda";
String type = cheeses.contains(x) ? "Gouda".equals(x) ? "Yummy Gouda" : "Cheese - but not Gouda" : "Maybe not dairy";
Ternary operator is not the equivalent of if-else in EVERY possible case. This is because both of possible results of using ternary operator are return values (e. g. simple printing to the console is not a return value so it can't be one of possible results in ternary operator).
Look, you can do it with if-else, but it's not possible with ternary operator:
if (x > 5) {
System.out.println("Statement is true");
else {
System.out.println("Statement is false");
}
You can't do it with ternary operator:
x > 5 ? System.out.println("Statement is true") : System.out.println("Statement is false");
When both of results of using ternary operator are considered as return values, they are then an equivalent of if-else.
Yes, it can be used, but off course in that case using -x doesn't make sense so it depends on what do you want to return when String is an input. You can do this:
("Cheese".equals(x) ? <some object of expected type X> : <some other object of expected type X>)
where X can be String on any other type. And remember to do "string".equals(x) instead of x.equals("string"). This prevents NullPointerException.
For primitive values you can use ==, but for objects you need to use equals method. There are some edge cases when you can use == on String, but they are not relevant to your case I guess and you can read about it outside of this topic.
PS: Some answers talk about if else statement, but that's not what question is about.
Can this be used like an if else on all accounts? For example, can you
compare strings with it?
I am pretty sure that by saying like an if else he means conditional operator which has if else like behaviour, not if else instruction itself.
Yes it can be used in Java; however note that x =="Cheese" isn't the proper way to compare strings in Java, you want something like "Cheese".equals(x).

Conditional operator for odd or even

I'm trying to write a program that that will find if there's an equal number of odds and even numbers in a given one, it's working great but it want to use conditional operator instead of these 4 rows (the // rows),
I'm getting this:
Syntax error on token "%", invalid AssignmentOperator
Can someone tell me why? What's wrong?
while(number!=0) {
//if(number%2==0)
//even++;
//else
//odd++;
number%2==0 ? even++ : odd++;
number/=10;
}
number%2==0 ? even++ : odd++;
This is not a statement. The result of a ternary must be assigned to something:
int x = number % 2 == 0 ? even++ : odd++;
However, this is stylistically quite awkward. I would use an if-else (i.e., what you originally had) over this pattern. Here you've created a temporary variable that you're never going to reuse, for the sole purpose of using a ternary.
It requires a variable at the left side at where you can place the value after the condition.
int tmp = (number%2 == 0)?even++:odd++;
number%2==0 ? even++ : odd++;
This statement is not assigning any value to number.As per my knowledge its always recommended for use if-else instead of ternary operator.
Because, in ternary operator the false/else part is compulsory to write, where in if-else else/false part is optional.
while(number!=0) {
//if(number%2==0)
//even++;
//else
//odd++;
int temp= number%2==0 ? even++ : odd++;
number/=10;
}
Now, temp variable is holding the value .

Single expression in ternary operator in Java

I know you can have
String answer = (5 == 5) ? "yes" : "no";
Is it somehow possible to have only:
String answer = (5 == 5) ? "yes";
It gives a compile error when I try.
NOTE: (5==5) is just an example. In its place will be statement which could be either true or false.
if one line is important
String answer = (5 == 5) ? "yes": null;
Since a String's default value is null.
You're looking for an if statement:
if (5 == 5)
answer = "yes";
Your idea is impossible because an expression (such as the conditional value) must always have a value.
In your code, if 5 != 5, the expression would have no value, which wouldn't make any sense.
No. you can't have it. You need to specify both the ? and :.
Use a straight if.

Categories