Java Equivalent to iif function - java

the question is simple, there is a functional equivalent of the famous iif in java?
For example:
IIf (vData = "S", True, False)
Thanks in advance.

vData.equals("S") ? true : false
or in this particular case obviously one could just write
vData.equals("S")

Yeah, the ternary op ? :
vData.equals("S") ? true : false

The main difference between the Java ternary operator and IIf is that IIf evaluates both the returned value and the unreturned value, while the ternary operator short-circuits and evaluates only the value returned. If there are side-effects to the evaluation, the two are not equivalent.
You can, of course, reimplement IIf as a static Java method. In that case, both parameters will be evaluated at call time, just as with IIf. But there is no builtin Java language feature that equates exactly to IIf.
public static <T> T iif(boolean test, T ifTrue, T ifFalse) {
return test ? ifTrue : ifFalse;
}
(Note that the ifTrue and ifFalse arguments must be of the same type in Java, either using the ternary operator or using this generic alternative.)

if is the same as the logical iff.
boolean result;
if (vData.equals("S"))
result = true;
else
result = false;
or
boolean result = vData.equals("S") ? true : false;
or
boolean result = vData.equals("S");
EDIT: However its quite likely you don't need a variable instead you can act on the result. e.g.
if (vData.equals("S")) {
// do something
} else {
// do something else
}
BTW it may be considered good practice to use
if ("S".equals(vData)) {
The difference being that is vData is null the first example will throw an exception whereas the second will be false. You should ask yourself which would you prefer to happen.

Related

Quick conditional without return value Java [duplicate]

I was wondering if it was possible to do a ternary operation but without returning anything.
If it's not possible in Java is it possible in other languages, if so which ones apply?
name.isChecked() ? name.setChecked(true):name.setChecked(false);
No, you can't. But what's the point of this over an if-else statement? Are you really trying to save 7 characters?
if (name.isChecked()) {
name.setChecked(true);
} else {
name.setChecked(false);
}
or if you prefer bad style:
if (name.isChecked()) name.setChecked(true); else name.setChecked(false);
Never mind the fact that you can just do (in this case):
name.setChecked(name.isChecked());
The point of the ternary or "conditional" operator is to introduce conditionals into an expression. In other words, this:
int max = a > b ? a : b;
is meant to be shorthand for this:
int max;
if ( a > b ) {
max = a;
} else {
max = b;
}
If there is no value being produced, the conditional operator is not a shortcut.
I was wondering if it was possible to do a ternary operation but without returning anything.
No it is not possible:
The 2nd and 3rd operands are required to be non-void expressions; i.e. they must produce some actual value.
"It is a compile-time error for either the second or the third operand expression to be an invocation of a void method." - JLS 15.25.
A ternary expression is an expression, and cannot be used as a statement.
"Certain kinds of expressions may be used as statements by following them with semicolons." ... and the ternary expression is not one of those kinds - JLS 14.8.
If you really, really want to use a ternary expression but not use the value of the expression, then the simplest thing is to assign the value to a dummy variable, and add an annotation to suppress the warning about the variable not being used.
But a better idea is to use a plain if statement.
If it's not possible in Java is it possible in other languages, if so which ones apply?
I'm a bit rusty, but I believe that C, C++ and Perl all allow arbitrary expressions to be used in places where their values are not used.
Sometimes, you can use ternary operation on method arguments to solve your request.
name.setChecked(name.isChecked() ? true : false);
By the way, the best solution for your problem is
name.setChecked(name.isChecked());
I assume the use case in the question is just a poor example because it's equivalent to the following statement:
name.setChecked(name.isChecked());
... which doesn't make sense either. But the intent is clear and there are indeed many relevant use cases.
The only viable and general solution is adding a helper method like this:
static void ternaryVoid(boolean condition, Runnable ifTrue, Runnable ifFalse) {
(condition ? ifTrue : ifFalse).run();
}
and using it like this:
ternaryVoid(name.isChecked(), () -> name.setChecked(true), () -> name.setChecked(false));
But it loses the elegance of ternary operator and worth the 'effort' only if used by multiple parts of the code and only if nanoseconds don't matter.
But what's the point of this over an if-else statement? Are you really trying to save 7 characters?
I'm surprised that such statements appear in a form of rhetorical questions. Yes, saving 4 lines and making the code more elegant is important, especially in the context of functional programming.
Moreover, it's at least arguable whether void methods return a complete Void. Essentially, they return a notification of a completed task. This is why logically, ternary expression makes sense equally regardless of whether it returns something or nothing:
condition ? doThis() : doThat();
Here is a real world example of a class which may process millions of incremental updates per second:
public class DataHandler {
private final TreeMap<Integer, Long> tree = new TreeMap<>();
public void onUpdate(int price, long amount) {
if (amount == 0) {
tree.remove(price);
} else {
tree.put(price, amount);
}
}
}
If allowed, the onUpdate() method would be a nice ternary expression like this:
public void onUpdate(int price, long amount) {
(amount == 0) ? tree.remove(price) : tree.put(price, amount); // compilation error
}
Fortunately, in some cases like this, both target methods return values, and these values are of the same type, which is Long in this case. This allows either to make the onUpdate method to return the previous amount at price (which is even useful)
public Long onUpdate(int price, long amount) {
return (amount == 0) ? tree.remove(price) : tree.put(price, amount);
}
... or alternatively (e.g. in case the method is determined by an interface), to use a dummy variable and suppress its uselessness warning:
public void onUpdate(int price, long amount) {
#SuppressWarnings("unused")
Long dummy = (amount == 0) ? tree.remove(price) : tree.put(price, amount);
}
Otherwise, these solutions are not applicable, and as answered by others, doesn't exist. For instance, one may try the following:
Consumer<Void> dummy = (x) -> {};
dummy.accept(/*...*/);
but interestingly, the second line compiles with neither anything nor nothing as an argument.
It seems the best general solution is the above helper method ternaryVoid().
You have to return some value and it will not work if you want it to act like a void method which performs some action without a returning a value.
Hope this helps...
In java following code isn't possible:
(your-condition) ? (true-statements) : (false-statements)
for sample you can't compile following snipet code :
(1==1) ? System.out.println("") : System.out.println("");
you achieve following compilation error:
The left-hand side of an assignment must be a variable

What is the point of == true in conditionals?

I'm learning C++ and java and I've noticed how if you have a conditional, whatever code follows will be executed if the condition is true, even if you don't explicitly write == true
Consider the following very simple C++ code:
bool c_plus_plus_is_cool(){
return true;
}
int main(){
if (c_plus_plus_is_cool()) {
cout << "C++ is cool!";
}
return 0;
}
Q: What is the difference between
if (c_plus_plus_is_cool())
and if (c_plus_plus_is_cool() == true) ?
And is this also the case in other languages (like Java (where I've been writing ==true all this time...)) ?
The == operator returns a boolean.
If you already have a boolean, == true will be no different from the original boolean; there is no point in writing it.
Similarly, use the ! operator instead of == false.
One exception to this is C# nullable booleans, where == true will be false for null.
Both C++ and Java have the same behaviour in this point and in both languages the == true is just redundant noise.
If you use the verbose syntax in Java so far then this is your own private style. Even in Java this is not the commonly used and accepted/recommended style.
There is actually no difference other than syntactical bloat brought by == true.
In C/C++ and pretty much every language, if and while encapsulate blocks of code that will only be executed if a condition is true. Explicitly putting an == true into your condition statement is redundant but some programmers prefer it; it's basically a style choice and will not affect the behaviour or speed of your program.
They both are same. The language implements the conditions as follows:
When it encounters the if statement, please check whether the condition is true.
Now, when we say this, it obviously allows you to do == , which
the compiler/interpreter will deal it by saying, are the data types or value
equal? If yes then proceed further.
Refer the flowchart
The piece of code:
bool c_plus_plus_is_cool(){
return true;
}
int main(){
if (c_plus_plus_is_cool()) {
cout << "C++ is cool!";
}
return 0;
}
is same as:
int main(){
if (c_plus_plus_is_cool() == true) {
cout << "C++ is cool!";
}
return 0;
}
No difference when == true is in if or while (or something similar like for or ternary operator), especially if the left value is already of type bool, and in your case it is.
If you need to explicitly convert a value to bool, plain explicit conversion (bool(expr)) looks much better.
THE ONLY case when that strange comparison is reasonable is when the value on the left of == belongs to a class that has a comparison operator taking bool as a second argument (though that generally means bad design:)). But it is not the case, so, to my mind, such coding convention is absolutely useless and rather ugly.
The second one is a bad habit that will give wrong answers in other contexts:
int f() {
return 3;
}
if (f() == true)
std::cout << "Won't get here\n";
if (f())
std::cout << "Will get here\n";

Type mismatch: cannot convert from Object to K when using conditional operator

I have the following code,
class Foo<K> {
public <T> T createK() {
return null;
}
public void foo() throws ClassNotFoundException {
K k = (1==1)?null:createK();
}
}
However, it didn't compile. It caused the following compilation error (Oracle Java 7) on the line with the conditional operator:
Type mismatch: cannot convert from Object to K
When I rewrite the foo() method as follows,
public void foo() throws ClassNotFoundException {
K k = null;
if (1==1)
k = null;
else
k = createK();
}
Then it compiles fine. How is this caused and how can I solve it?
Although the conditional operator is not exactly same as if-else conditional, but this is a different issue.
This is a known bug with type inference of generic type parameter with conditional operator which doesn't work as expected.
The solution is to provide explicit type argument:
K k1 = (1==1) ? null : this.<K>createK();
...this would work, however with compiler warning - Dead Code (of course, due to 1 == 1 part). Note, how we need to explicit use this to invoke the method with explicit type argument. Simply doing <K>createK() won't work.
Adding the explicit type argument with method invocation - this.<K>createK(); forces the type T to be inferred as K, which is otherwise inferred as Object.
However, I suspect that your doubt is really related to the type inference. It's just a coincidence that the issue came out to be that. Even though, to get some idea about how conditional operators work in different situations, and what the type of its result is, you can schedule a visit to JLS ยง15.25 - Conditional Operator
No, the ternary (i.e. the ? :) is a very different beast from if ... then ... else.
The ternary is an operator and the two alternatives have to be expressions evaluating to the same type.
if ... then ... else is a convenient programming construct; the bits in between are statements not expressions.
In fact, the entire ternary construct is an expression, whereas the if ... then ... else is itself a statement. (You can assign a value to a ternary; e.g. foo = ... ? ... : ... but foo = if ... then ... else is meaningless and therefore syntatically invalid.)
Your code does not compile because the types of both sides of a conditional expression must match. There is no such requirement for the if statement - in fact, there is no requirement for the two parts to be related to each other in any way, let alone assigning the same variable.
Adding a cast fixes your conditional (demo on ideone):
K k = (1==1)?null:(K)createK();
Those operators are different.
1) In case of if ... then ... else there is no limitations of actions
2) Ternary operator. Using that both sides must have the same type.
You can fix everything with cast:
K k = (1 == 1) ? null : (K)(createK());
Using condition ? valueA : valueB operator is meaningful only if there is an Lvalue,
Lvalue = condition ? valueA : valueB
The exact meannig of this operator can be transformed to an if else statement:
int y,z;
int x= (y==0) ? y+1 : z+3
this ends up to be the same as:
if(y==0)
{
x=y+1;
}else
{
x = z+3;
}

Is there a shorthand way to write the Javascript code 'a||"text"' in Java?

When I need to display a value that might be null/undefined in Javascript, I usually just write:
console.log(a||"");
Or something similar. Is there a similar way to do this in Java other than:
System.out.println(a!=null?a:"");
I think that your System.out.println(a!=null?a:""); is a very clear way to output what you are looking for.
It uses the ternary operator and seems to make sense.
(condition) ? (if true) : (if false);
The best you can do besides using the ternary operator is to create a very short method to do the same. Perhaps "ns" for "nullable string":
public static String ns(String nullableString) {
return nullableString == null ? "" : nullableString;
}
Then you can write "System.out.println(ns(a));" However, the ternary operator is clearer - I would only do something like the above if I were doing this all over the place.
You have ternaries:
a != null ? a : ""
There isn't, as the others answers suggest. That is because in JS, boolean operators don't necessarily return booleans, they return the value of the object that caused the expression to short-circuit. However, in Java, as in C and other languages, boolean operators always return boolean, so you don't have that convenient way of defaulting a value a = b || c or to prevent a null pointer a = b && b.getValue()
You can do a function that doesn't print null when its null.
I don't know java but a prototype will be
function safePrint(object a)
{
System.out.println(a!=null?a:"");
}
and then just write
safePrint(a);
Although if you are looking for short code use an interpreted language like javascript or perl. compiled languages like java is just not meant for fast and short coding.
If the variable is not initialized, java will not compile. Undefined is unacceptable in Java.
If you have a variable named "blueberry" and you want to display the value on the console, you can do this:
System.out.println(blueberry);
This code will display "null" on the console if blueberry is null.
Here is a simple demonstration
public class Outty
{
public static void main(String[] args)
{
String blueberry = null;
System.out.println(blueberry);
blueberry = "7";
System.out.println(blueberry);
}
}

Getting confused with == and = in "if" statement

I know that we cant use assignment operator in if statements in java as we use in any other few languages.
that is
int a;
if(a = 1) { }
will give a compilation error.
but the following code works fine, how?
boolean b;
if(b = true) { }
EDIT : Is this the exception to rule that assignment cant be used in if statement.
Because the "result" of an assignment is the value assigned... so it's still a boolean expression in the second case. if expressions require the condition to be a boolean expression, which is satisfied by the second but not the first. Effectively, your two snippets are:
int a;
a = 1;
if (a) { }
and
boolean b;
b = true;
if (b) { }
Is it clear from that expansion that the second version will compile but not the first?
This is one reason not to do comparisons with true and false directly. So I would always just write if (b) instead of if (b == true) and if (!b) instead of if (b == false). You still get into problems with if (b == c) when b and c are boolean variables, admittedly - a typo there can cause an issue. I can't say it's ever happened to me though.
EDIT: Responding to your edit - assignments of all kinds can be used in if statements - and while loops etc, so long as the overall condition expression is boolean. For example, you might have:
String line;
while ((line = reader.readLine()) != null)
{
// Do something with a line
}
While I usually avoid side-effects in conditions, this particular idiom is often useful for the example shown above, or using InputStream.read. Basically it's "while the value I read is useful, use it."
For if you need an expression that evaluates to boolean. b = true evalueates to boolean but a = 1 evaluates to int as assignments always evaluate to the assigned values.
The reason the second code works okay is because it is assigning 'b' the value of true, and then comparing to see if b is true or false. The reason you can do this is because you can do assignment operators inside an if statement, AND you can compare against a boolean by itself. It would be the same as doing if(true).
In java, you don't have implicit casting. So non-boolean values or not automatically transformed to booleans.
In the first case, the result of the statements is an int, which is non-boolean, which will not work. The last case, the result is boolean, which can be evaluated in an if-statement.
The rule is not that "assignment can't be used in an if statement", but that "the condition in an if statement must be of type boolean". An assignment expression produces a value of the type being assigned, so Java only permits assignment in an if statement if you're assigning a boolean value.
This is a good reason why the style if (foo == true) should be avoided, and instead simply write if (foo).

Categories