Ternary Operators Java [duplicate] - java

This question already has answers here:
Ternary Operator
(4 answers)
Closed 5 months ago.
Is there a way to implement this in a ternary operation. I'm very new to that ternary stuff, maybe you could guide me.
if(selection.toLowerCase().equals("produkt"))
cmdCse.setVisible(true);
else
cmdCse.setVisible(false);
This one doesn't seem to work.
selection.toLowerCase().equals("produkt")?cmdCse.setVisible(true):cmdCse.setVisible(false);

In this case, you don't even need a ternary operator:
cmdCse.setVisible(selection.toLowerCase().equals("produkt"));
Or, cleaner:
cmdCse.setVisible(selection.equalsIgnoreCase("produkt"));
Your version:
selection.toLowerCase().equals("produkt")? cmdCse.setVisible(true): cmdCse.setVisible(false);
is semantically incorrect: ternary operator should represent alternative assignments, it's not a full replacement for if statements. This is ok:
double wow = x > y? Math.sqrt(y): x;
because you are assigning either x or Math.sqrt(y) to wow, depending on a condition.
My 2cents: use ternary operator only when it makes your program clearer, otherwise you will end up having some undecipherable one-liners.

Perhaps
cmdCse.setVisible(selection.toLowerCase().equals("produkt"));

The ternary operator isn't exactly like an if statement. A ternary operator has to "return" something from both sides, so putting void method calls like setVisible() there won't work.
Instead, you could do something like this without ternary operators at all:
cmdCse.setVisible(selection.toLowerCase().equals("product"));
But just to demonstrate the point, the ternary equivalent would look something like this:
cmdCse.setVisible(selection.toLowerCase().equals("product") ? true : false);
Notice how now the ternary operator "returns" true or false on both sides instead of simply calling a void method.

I think this will work for you
cmdCse.setVisible(selection.toLowerCase().equals("produkt"));

Directly from the docs
Use the ?: operator instead of an if-then-else statement if it makes your code more readable; for example, when the expressions are compact and without side-effects (such as assignments).
In your case cmdCse.setVisible(true / false); doesn't return anything, and the operation also has side effects (it changes state of cmdCse), so the conditional operator cannot be used here (when you do use the operator, both of the ? and : branches must have the same return type).
As an aside, please note that .. ? .. : .. should be referred to as the conditional operator

On the issue of using exceptions
I want to answer the issue of the exceptions here as this question is a duplicate for another question concerning throwing exceptions from a ternary expression, but this is not addressed in the above answers.
The general consensus is that it cannot be done directly as in:
public Character next() {
return hasNext() ? s.charAt(cur++) : throw new NoSuchElementException(); // compilation error
}
will give you a compilation error, but as Clement pointed out it can be done via a declared extra function. It can also be done via (ab-)using lambda expressions.
public Character next() {
return hasNext() ? s.charAt(cur++) : ((Function<Integer, Character>) x -> {throw new NoSuchElementException();}).apply(1);
}
for sure this is not that pretty (it is pretty ugly) and I would not recommend to do that for readability purposes, but sometimes there are circumstances which might warrant exceptionally doing that. If someones figures out a way to do it without the cast it would be a bit more readable.
If you had a function throwNoSuchElementException() defined somewhere that you use more than once, it would look a bit more readable:
public Character next() {
return hasNext() ? s.charAt(cur++) : throwNoSuchElementException();
}
(P.S.: I included this answer for completeness sake, as I asked myself can it really be not done?)
(P.S.S.: If the exception to be thrown is not a runtime exception this will not work so easily and would require even more handstands - not really worth it)

Here are my tips, if you need to set things to booleans, then simple use setBoolean(condition), else, if you need to set a variable to a non boolean value, then use var=condition?result1:result2(or the variable itself if you don't want to change if condition is false), otherwise, use if else.

Related

TernaryOperator (? :) for functions Java. How close we can get? [duplicate]

This question already has answers here:
Java: Ternary with no return. (For method calling)
(6 answers)
Closed 4 years ago.
Java has ternary operator, that works on variables:
(a > 0) ? b++ : c--;
What is a, b, c were functions? I tested something like (a returns boolean, b & c are void):
a() ? b() : c();
but even my Eclipse does not allow that.
How close could I get to this programmatically (to generate functionality to make this with minimum amount of lines)?
I know in other languages like Javascript I could just pass function as parameter, but I have not met similar in Java.
Edit
We have gone in discussion to sidewals because of bad constellation of question, but here is what I want, and it is a real world problem:
What I want to achieve is single-liner to call second or third function based on return value of the first.
With minimum amount of code of course.
What I had tried was that ternary that is made to other things, that I know now.
As others have already explained, the conditional operator is an expression that evaluates to a value, and can thus not be applied to void methods.
If you need a one-liner discarding any return values, use a simple if-else:
if (a()) b(); else c();
If you go through Java Ternary Operator let's you assign a value to a variable based on a boolean expression — either a boolean field, or a statement that evaluates to a boolean result (Its used for assignment). In above you are trying to call functions with return value void that is not allowed in Ternary Operator in java.
The ternary operator, also known as the conditional operator, can be
used as an alternative to the Java if/then/else syntax
You can only use the ternary operator as an expression, not a statement. It's not simply alternative syntax for an if-else - the point is that if a() returns true, the entire expression resolves to the result of b(), else the entire expression resolves to the result of c().
As such, it doesn't make sense if b and c return void. They must return something, and the most specific type that they share will be the resulting type of the whole expression.

Conditional method calling by abusing ternary wrapped in if statement?

Recently I was doing a code review and came across this guy:
if(!sharePermission.isExpired() ? activePermissions.add(sharePermission) : expiredPermissions.add(sharePermission));
Basically using a ternary expression to call methods that return a boolean value and wrapping it in an if(...) statement to satisfy the requirement of being a standalone statement. Is this more or less valid than
if(!sharePermission.isExpired())
activePermissions.add(sharePermission);
else
expiredPermissions.add(sharePermission);
if you really need to condense your code to one line? Is any sort of extra space allocated for the value returned from the ternary expression when wrapped in the if(...) ?
I'm not a fan of either of them, just curious.
It's an abuse of the if statement to do that, never mind the conditional expression.
It would be cleaner to write either a full if statement, or to use the conditional operator to select a list to add to:
List<Permission> list = isExpired() ? expiredPermission : activePermission;
list.add(sharePermission);
There is no assignment happening, only an evaluation of a boolean condition. No extra memory is allocated for the result of the evaluation.
Using a ternary expression to emulate a ternary statement, however, is grossly unorthodox. It is going to reduce readability of your code, without bringing any additional benefit. Hence, using a plain if with an else is a better alternative.
Note that if activePermissions and expiredPermissions are of the same type, you can use a ternary expression to decide between the targets of the add call, as follows:
(sharePermission.isExpired() ? expiredPermissions : activePermissions).add(sharePermission);
The ternary equivalent for the if..else that you are looking for is something like -
(!sharePermission.isExpired() ? activePermissions : expiredPermissions).add(sharePermission); // no if here
is equivalent to
if(!sharePermission.isExpired()) {
activePermissions.add(sharePermission);
}
else {
expiredPermissions.add(sharePermission);
}

Replacing an if statement with a disjunction

Just for fun, I was trying to replace:
if (set1.add(x) == false)
{
set2.add(x);
}
with:
set1.add(x) || set2.add(x);
However, Eclipse complains:
Syntax error on token "||", invalid AssignmentOperator
The left-hand side of an assignment must be a variable
Could anybody shine some light onto these error messages? They don't make much sense to me.
As #qqilihq said in the comments try to do
boolean temp = set1.add(x) || set2.add(x);
or more awkward:
if(set1.add(x) || set2.add(x));
According to documentation java statements which can end with a semicolon are:
Assignment expressions
Any use of ++ or --
Method invocations
Object creation expressions
What you've written is not a statement it's an expression. Here you can find more about statements and expressions. So simple but worth to look.
There are a number of answers far, but I agree with Bohemian's answer that the most straightforward simplification (although it doesn't use ||) is this:
if ( !set1.add(x) ) set2.add(x);
That doesn't explain the error message though. Mustafa Genç comes closer on this, but I think it's worthwhile to look at the language specification here. exp1 || exp2 is an expression, and the problem here is that you're trying to use it in a context where a statement is expected. According to 14.8. Expression Statements, some kinds of expressions can be used where statements are expected by attaching a semicolon:
14.8. Expression Statements
Certain kinds of expressions may be used as statements by following
them with semicolons.
ExpressionStatement:
StatementExpression ;
StatementExpression:
Assignment
PreIncrementExpression
PreDecrementExpression
PostIncrementExpression
PostDecrementExpression
MethodInvocation
ClassInstanceCreationExpression
An expression statement is executed by evaluating the expression; if
the expression has a value, the value is discarded.
The reason that you can't do what you're trying to do, though, is that not every expression can be used as a statement. However, it does discuss some ways to work around this. From the same section of the specification (emphasis added):
Unlike C and C++, the Java programming language allows only certain
forms of expressions to be used as expression statements. Note that
the Java programming language does not allow a "cast to void" - void
is not a type - so the traditional C trick of writing an expression
statement such as:
(void)... ; // incorrect!
does not work. On the other hand, the Java
programming language allows all the most useful kinds of expressions
in expressions statements, and it does not require a method invocation
used as an expression statement to invoke a void method, so such a
trick is almost never needed. If a trick is needed, either an
assignment statement (§15.26) or a local variable declaration
statement (§14.4) can be used instead.
This approach is what the first snipped in Reik Val's answer is using:
boolean temp = set1.add(x) || set2.add(x);
I would just:
if (!set1.add(x))
set2.add(x);
The statement
boolean temp = set1.add(x) || set2.add(x);
and any variation thereof is dangerous. You'll hardly ever know what happens there. Note that the right expression is NOT evaludated iff the first expression is true. That is, the attempt to add it to set2 will only be made if it was not yet contained in set1.
EDIT: Now, reading the question again, it seems that this was exactly what you intended. So I think that the anser https://stackoverflow.com/a/21755051 by Mustafa Genç is the relevant here
Usually, you should write clearly what you want to do
boolean wasNotContainedInSet1 = set1.add(x);
boolean wasNotContainedInSet2 = set2.add(x);
boolean wasNotContainedInAnySet =
wasNotContainedInSet1 | wasNotContainedInSet2;
or
boolean wasNotContainedInSet1 = set1.add(x);
if (!wasNotContainedInSet1) {
set2.add(x);
}
or whatever...

Which has better performance: test != null or null != test [duplicate]

This question already has answers here:
object==null or null==object?
(11 answers)
Closed 2 years ago.
Consider the following two lines of code
if (test ! = null)
and
if (null != test)
Is there is any difference in above two statements, performance wise? I have seen many people using the later and when questioned they say its a best practice with no solid reason.
No difference.
Second one is merely because C/C++ where programmers always did assignment instead of comparing.
E.g.
// no compiler complaint at all for C/C++
// while in Java, this is illegal.
if(a = 2) {
}
// this is illegal in C/C++
// and thus become best practice, from C/C++ which is not applicable to Java at all.
if(2 = a) {
}
While java compiler will generate compilation error.
So I personally prefer first one because of readability, people tend to read from left to right, which read as if test is not equal to null instead of null is not equal to test.
They are exactly the same. The second one can make sense when using equals:
if("bla".equals(test))
can never throw a NullPointerException whereas:
if(test.equals("bla"))
can.
There is no performance difference but I personally find the second one being confusing.
Second one looks for me like "Yoda condition", i.e. if(2 == x) ... and is much less readable.
It's best practice to avoid some basic typo's that most modern IDE's will pick up, because sometimes you want to do comparisons between more complex types that are not null and end up doing accidental assignments. So the pattern remains the same, but I've never seen this linked to performance and have never seen it generate special byte code.
The idea is to have the static, known value first, so you can't throw any kind of weird exception when you perform the comparison.
Neither of the two methods are "more correct" though, so it's entirely up to you to decide what you wish to use.
there is no difference. But in second way you avoid the typo like test = null. Beacause in second way you'll get compiler error.
It's not a best practice to use the latter one. Both are equivalent, but the former is easier to read.
This "best practice" comes from C where boolean don't exist. Integers are used instead, and if (foo = 1) is not a syntax error, but is completely different from if (foo == 1).
In Java, only boolean expressions can be inside an if, and this practice doesn't make much sense.
There is no really different between two form. There is no performance issue but there are following notes:
First form is readable for code reader, because people usually read codes Left-To-Right.
Second form is better for code writer, because in java = operator is for assignment and == operator is for test equivalent, but people usually using in if statement = instead of ==, by second approch developer getting Compile-Time-Error because null can't use in Left-Side of a assignment statement.

what is the standard guideline to declare the "==" condition? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the difference between these (bCondition == NULL) and (NULL==bCondition)?
please see the below code:-
if(myVariable==5)
{
//some logic
}
one of my friends says that this is not a good way to write the code as its not per guidelines, however he dont have any reason to it. Is there is a chance of exception with above code or accidental modification?? According to him the better way would have been
if(5==myVariable)
{
//some logic
}
please let me know which is a better way and why??? Do provide links if u have any.
The only reason to write:
5 == variable
instead of
variable == 5
is that in the former case if you incorrectly put an assignment (single =) in place you will get a compile time error because you are trying to overwrite a constant.
However any decent compiler will give you a warning if you do:
if (variable = 5)
so IMHO it's not worth worrying about. I always use the latter if (var == num) form.
However in Java there is a common pattern that is worth using. When testing a string for equality, one should use:
if ("constant".equals(variable)) { ... }
instead of:
if (variable.equals("constant")) { ... }
since the latter can trigger a null pointer exception, and the former cannot.
The reversal is preferable in some languages like C, where
if (x = 5) {
...
}
would accidentally assign x to the value 5 if you mistype = instead of ==. By reversing the two arguments the compiler would rightfully object to you reassigning the value 5.
Unlike C/C++, for languages such as Java it's not such an issue since
if (x = 5) {
...
}
isn't a valid statement. I still follow the above practise however. I don't have to rethink when swapping between Java and C/C++.
Both are same. select which ever you find more readable.. I would go with first
For that specific case, it's technically safer to do 5 == variable because then if you accidentally say 5 = variable the compiler will complain. On the other hand, variable = 5 is perfectly legal.
This convention is to prevent you from accidentally writing if (myVariable=5) when you mean if (myVariable==5).
For ==, it doesn't matter a bit what order you do it in.
Your friend mentioned "guidelines"-- perhaps it's a business rule? Albeit an arbitrary and semi-pointless one...
It's immaterial. I prefer the first one, because it's more readable.
I hope you're aware that using == is not always correct for reference types. In those cases you should prefer equals. THEN it matters, because you want to avoid null pointer exceptions. It's best to dereference the instance that cannot be null in that case.
There is no such guildline I found.
First approach should be followed because it is more readable.
i think if you what to know if they are equals it's fine then.
but if you want to know about string, then i more appropriated use '.equals'.
e.g:
object.equals("something");
The only thing I can think of is to avoid possible syntax errors of the kind constant = expression, or to avoid mangled operator overload in C++. In Java both expressions are syntatically valid and picking one over the other is a matter of choice.

Categories

Resources