Java: Ternary with no return. (For method calling)
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.
Can Java's ternary/conditional operator (?:) be used to call methods instead of assigning values?
Think of ternary operators like a method in this case. Saying a ? b : c
is (for the intents and purposes you're considering, see lasseespeholt's comment) equivalent to calling the pseudocode method:
ternary(a, b, c)
if a
return b
else
return c
which is why people can say things like x = a ? b : c
; it's basically like saying x = ternary(a, b, c)
. When you say (condition) ? doThis() : doThat()
, you're in effect saying:
if condition
return doThis()
else
return doThat()
Look what happens if we try to substitute the methods for what they return
if condition
return ???
else
return ???
It doesn't even make sense to consider it. doThis()
and doThat()
don't return anything, because void
isn't an instantiable type, so the ternary
method can't return anything either, so Java doesn't know what to do with your statement and complains.
There are ways around this, but they're all bad practice (you could modify your methods to have a return value but don't do anything with what they return, you could create new methods that call your methods and then return null, etc.). You're much better off just using an if
statement in this case.
EDIT Furthermore, there's an even bigger issue. Even if you were returning values, Java does not consider a ? b : c
a statement in any sense.
JAVA calling a method using a ternary operator
This will not work, as it is not the intended use of the ternary operator.
If you really want it to be 1 line, you can write:
if (x==1) doThisMethod(); else doThatMethod();
java ternary operator return function result
Sure: make your method "return" String
:
public String throwException(int index, String name) throws TelegrammException
{
throw new TelegrammException("Wrong telegramm format at position: "
+ index + "; Name: " + name);
}
Now, this never actually returns a String
because it doesn't complete normally. But you can now use this in a conditional expression:
String result = condition ? "Something" : throwException(index, name);
But: this is an abuse of syntax. Just stick with a plain old if statement:
if (condition) {
result = "Something";
} else {
throwException(index, name);
}
You might also then want to consider making the return type of the method TelegrammException
:
public TelegrammException throwException(int index, String name) throws ...
This allows you to throw
at the call site:
throw throwException(index, name);
which allows you to indicate to the compiler (and humans reading your code) that execution doesn't continue beyond there, which may help you with things like definite assignment/return value requirements.
Use ternary alike method for calling methods
You can only write
testString.equals("test") ? doSomething() : doSomethingElse();
if doSomething()
and doSomethingElse()
both return something, and those somethings have either exactly the same type, or are covariant types. Setting both functions to return a boolean
would be sufficient.
This is because the entire thing is an expression, and an expression has a value as well as a well-defined type.
If you are not wanting to do anything with the return value, then use an if
statement.
TernaryOperator (? :) for functions Java. How close we can get?
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();
Java Ternary without Assignment
Nope you cannot do that. The spec says so.
The conditional operator has three operand expressions. ? appears
between the first and second expressions, and : appears between the
second and third expressions.The first expression must be of type boolean or Boolean, or a
compile-time error occurs.It is a compile-time error for either the second or the third operand
expression to be an invocation of a void method.
[EDIT]
Since you asked about reflection, here's a solution. I'm not recommending this. I'm posting it only because you asked.
public class MyCall
{
public void a(){System.out.println("a");}
public void b(){System.out.println("b");}
public static void main(String... args)
{
new MyCall().go();
}
public void go()
{
Class<? extends MyCall> class1 = this.getClass();
Method aMethod = class1.getMethod("b", null);
Method bMethod = class1.getMethod("a", null);
Object fake = false ? aMethod.invoke(this, null) : bMethod.invoke(this, null);
Object fake2 = true ? aMethod.invoke(this, null) : bMethod.invoke(this, null);
}
}
At the end of the day you've got to ask yourself if being succint improves your code's readability (think for-each loop). None of these solutions improve the code's readability IMHO. If I were you I'd rather go with this.
if(condition)
a();
else
b();
I'm actually for including braces even when loops only contain a single line, but since you're going after crisp code, the snippet above should do.
Invalid java syntax using ternary operator
You need to assign (or return) the Object
you're polling. Something like
public void pop(){
Object obj = queue1.isEmpty() ? queue2.poll() : queue1.poll();
}
or (what I think you really want) - something like
public Object pop(){
return queue1.isEmpty() ? queue2.poll() : queue1.poll();
}
See also JLS-15.25. Conditional Operator ? :
.
Related Topics
Android 6.0 Open Failed: Eacces (Permission Denied)
Swagger Ui Is Not Loading Swagger API Json
What Is a Question Mark "" and Colon ":" Operator Used For
Why We Use If, Else If Instead of Multiple If Block If the Body Is a Return Statement
What Is a Good Use Case for Static Import of Methods
Convert HTML Character Back to Text Using Java Standard Library
Creating Multiple Log Files of Different Content with Log4J
By Default, Jsf Generates Unusable Ids, Which Are Incompatible with the CSS Part of Web Standards
Copy a Stream to Avoid "Stream Has Already Been Operated Upon or Closed"
Eclipse: How to Build an Executable Jar with External Jar
Selecting Nth-Of-Type in Selenium
Noclassdeffounderror: Wrong Name
Programmatically Getting the MAC of an Android Device
How to Use a Tablename Variable for a Java Prepared Statement Insert